challenges

Next.js Data Fetching: Part 4

Workshop context

Before this workshop

  • In previous workshops, we created a status state and updated it to indicate a fetch in progress.

This workshop

  • In this workshop, we’re going to handle the error cases for the fetch.

After this workshop

  • In the next workshop, we’ll abstract the fetch and state logic into a custom hook .

Workshop goal

By the end of this workshop, your application will:

  1. Set the status state to “error” if:
    • an error occurred during fetch
    • the response is not ok
    • the returned json does not have a quote property
  2. Store a string version of the error in a new state variable called error.

Note: like the last workshop, there is no UI here. You’ll want to use console.log to examine the state for now.

Hints

Hint 1 Use try/catch within handleClick to catch errors with the fetch call.

Hint 2 You can capture the exception that was thrown with exceptionVar syntax . Conventionally, this exception variable is given the name error (see line 3 of this example ).

Hint 3 Suppose you’ve used error as the string for the exception variable (see previous hint). You can get the string version of the thrown exception within the catch block by using the toString() method : error.toString()

Since the type of error is technically unknown, you’ll need to use optional chaining to satisfy TypeScript: error?.toString().

Hint 4 For the ok and json parameter errors, you can throw an Error within the try block if either of those conditions is true. Once an error is thrown, the code in the try block will stop executing and the catch block will take over (using the thrown error as the exception).

Resources