ERROR HANDLING IN NEXT 13

As a web developer, you’re constantly on the lookout for ways to simplify your work, and if you’re not yet familiar with?Next.js 13, it’s about time you got acquainted with it. This version of Next.js has been available for a few months now and comes loaded with some fantastic features that have the potential to revolutionize your web development. However, it’s important to note that it’s currently in beta and should not be used in production. That said, you can still experiment with it and try out some of its new features, such as the?error.(js|jsx|ts|tsx)?file, which allows you to create an Error Boundary for each specific page. But be aware that to use Next.js 13’s new features, you must utilize the new?app?directory.

I’ve created two new folders called?counter?and?components?inside the?app?directory. Let’s take a closer look at the contents of these folders.

The template file,?template.tsx, will serve as the foundation for the counter page. Let’s dive in and take a closer look at the contents of our file.

import { FC } from "react";

interface CounterTemplateProps {
    children: React.ReactNode | React.ReactNode[];
}

const CounterTemplate: FC<CounterTemplateProps> = ({ children }) => {
    return (
        <div>
            <h1>Counter</h1>

            {children}
        </div>
    );
};

export default CounterTemplate;        

The template accepts a single prop, children, which can contain any additional elements or components that we may want to include within the page. The component includes a basic heading and renders the children prop directly below it.

We are going to take a closer look at the?page.tsx?file. This file imports and renders the?Counter?component, which contains all of the logic for our counter.

import Counter from "../components/Counter";

const CounterPage = () => {
    return <Counter />;
};

export default CounterPage;        

The?Counter?component is implemented as a functional component that employs state hooks to manage the counter’s value. Additionally, it features buttons that enable incrementing and decrementing of the value. If the counter value becomes less than 0 or greater than 3, an exception is thrown.

"use client";

import { useEffect, useState } from "react";
import styles from "./counter.module.css";

const Counter = () => {
    const [counter, setCounter] = useState<number>(0);

    useEffect(() => {
        if (counter < 0 || counter > 3) {
            throw new Error("The value is out of range");
        }
    }, [counter]);

    const incrementCounter = () => {
        setCounter((prev: number) => prev + 1);
    };

    const decrementCounter = () => {
        setCounter((prev: number) => prev - 1);
    };

    return (
        <div>
            <p>{counter}</p>

            <div className={styles.buttonsContainer}>
                <button className={styles.button} onClick={decrementCounter}>
                    -
                </button>
                <button className={styles.button} onClick={incrementCounter}>
                    +
                </button>
            </div>
        </div>
    );
};

export default Counter;        

I’ve included some initial styles for the?Counter?component in the?counter.module.css?file, which you’ll find below. You can customize these styles to suit your preferences or add new ones as needed.

.buttonsContainer {
    display: flex;
    column-gap: 0.625rem;
}

.button {
    padding: 0.5rem 1.5rem;

    font-size: 1rem;
}        

Lastly, we will create the?error.tsx?file. This file takes two props: error and reset. The error prop contains the thrown error, while the reset function enables you to return to the page.

"use client";

import { FC } from "react";

interface CounterErrorProps {
    error: Error;
    reset: () => void;
}

const CounterError: FC<CounterErrorProps> = ({ error, reset }) => {
    return (
        <div>
            <p>{error.message}</p>

            <button onClick={reset}>Reset</button>
        </div>
    );
};

export default CounterError;        

If you are currently using the?npm run dev?or?yarn dev?commands in your Next.js application folder, and then navigate to?https://localhost:3000/counter, you should be able to see a page that looks similar to this:

After clicking the increment or decrement buttons, the?error?file will be activated in case the counter value goes beyond the range of 0 to 3. This will result in a page that looks like this:

When you click the Reset button, the counter will be displayed again.

I would love to hear your thoughts and opinions on the content, so please feel free to leave a comment and let me know what you think.

要查看或添加评论,请登录

DANIEL OLEABHIELE的更多文章

社区洞察

其他会员也浏览了