challenges

Next.js Data Fetching: Part 3

Workshop context

Before this workshop

  • The previous workshop in this series displayed a random quotation upon clicking a button.

This workshop

  • This workshop will update the UI to give the user feedback when the quotation is loading.

After this workshop

  • Later workshops in this series will handle errors retrieving the quotation, and conditionally display content depending on the state.

Workshop goal

By the end of this workshop your app should reflect (using state values) when the fetch is in progress.

  1. Create a new state variable called status. Limit this variable to three possible values: “idle”, “loading” and “error” (the “error” is in anticipation of the next workshop).
  2. There aren’t UI updates for this workshop, but you can check your state by printing to the console via console.log.

Hints

Hint 1 Create a new type called Status for the status state. This should be limited to the three possible values listed above.

For guidance, check out the TypeScript literal types docs, especially the code that follows “But by combining literals into unions…“.

You can also go to the deprecated docs that (in my opinion) are more clear on this topic, reading less like a narrative and more like a reference work.

Hint 2 At the beginning of handleClick, update the state to indicate the fetch is loading. After the async functions have completed, update the state to indicate that the fetch is no longer loading.

Hint 3 Because the console.log of the state is originating from the React code running in the browser, the result will show up in the browser JavaScript console (for example, in Chrome ).

Resources