challenges

Next.js Data Fetching: Part 1

To prepare for this series, you’ll need to fork or clone the scaffolding repository . Take a look at the README for instructions to install and run the app.

Series context

Before this series

  • The previous series, React Components , built low-level components (Button, Card and Spinner) for this application.

This series

  • This series (Next.js Data Fetching) will build an app that fetches and displays a random quote.
  • At the end of this series, the application will display a random quote from the server. Here’s an example:
a web page with a button, dotted separator and blue card containing quotation text

After this series

Workshop goal

By the end of this workshop you should have an endpoint on the server that serves a random quotation.

Notes

  • See src/helpers/random-quotes.ts for a function to return a random quote.
  • The quotations in data/quotes.ts were assembled from two Kaggle datasets . The quotes do not necessarily reflect the views of this instructor. 😅
  • You may notice grammatical errors and/or unnecessarily gendered language in some the quotes. We’ll take care of these issues in the next workshop series (AI Style Generator).

Hints

Hint 1 Create a Next.js route handler at src/app/api/get-quote-styles/route.ts (a note about the directory name: for this series we’re just getting the quote; the style will come in the next series).

Hint 2 The file should export a GET function that runs the getRandomQuote function from src/helpers/random-quotes.ts, and returns JSON (something like '{"quote": <random quote>}' where <random-quote> is the quotation returned by getRandomQuote).

Hint 3 To test your route handler:

  1. Run npm run dev from the top level of the app in the terminal.
  2. Access http://localhost:3000/api/get-quote-styles to hit the endpoint and see the result in your browser. Since you’re retrieving a random quote, the response should be different every time you refresh this page.

Hint 4 If your endpoint isn’t functioning the way you think it should be, there are two places to check for errors:

  1. the browser JavaScript console (for example, in Chrome )
  2. the command-line where the server is running (where you ran npm run dev to start the server).

Resources