challenges

Next.js Data Fetching: Part 6

Workshop context

Before this workshop

  • In previous workshops, we created an endpoint and executed a fetch call to the endpoint upon button click. We also managed the loading and error states.

This workshop

  • In this workshop, we’re going update the UI according to the status, to give the user better feedback.

After this workshop

  • In the next series, we’re going to use the OpenAI Node SDK to generate colors and fonts appropriate for the quote. We’ll also create an interface for the user to enter their own quotation.

Workshop goal

By the end of this workshop, your app will:

  1. Display a loading Spinner (and no quote or empty card) while the fetch is in progress.
  2. Display an error Card if there’s an error with the request.
    • the card should have background color: Tomato 11 , text color: white
    • the card should have an h2 heading of “An error occurred”
    • if the error prop (type: string) is defined, add the error beneath the heading.
    UI with a 'use random quote' button, a horizontal dotted line, and a red card with a heading that reads 'An error occurred', and contents that read 'TypeError: Malformed content'
  3. Only show the quote card when there’s a quote to display. For example, on load, the app should look like this: UI with a 'use random quote' button and dotted separator; no card

Hints

Hint 1 Create a separate ErrorCard component, that takes an optional string prop error, and returns a Card that matches the spec. Use this to display the error card.

You can call npm run new-component ErrorCard from the terminal from MacOS and Linux to create the files for the component. Since new-component isn’t guaranteed to work on Windows, Windows users can create files manually, using the new-component README for reference.

Hint 2 To keep the Home component high level, create a new component that manages UI based on state.

I called this component QuoteContent and created it with the new-component script from the previous hint. The component shoult take relevant state as props.

Use conditional return to return different JSX depending on the state values.

Hint 3 Both QuoteComponent.tsx and hooks/use-quote-styles.tsx need the Status type (QuoteComponent.tsx needs Status to set the prop type, and use-quote-styles.tsx needs Status to set the state type).

To share the type between the two files, move the definition to a new file (say, src/types/index.ts) and import Status each of the files that uses the type.

Resources

React docs on conditional return