Nextjs
not only allows us to setup basic and dynamic routes, it also allows us to use a similar pattern for defining API routes. In this video we will setup two API routes, consume the data in our React
components with react-query
's useQuery
hook.
Domitrius Clark: [0:00] Next.js handles all of its routing through its pages directory. We've created a user and users directory inside of pages and now have routes for them, but how do we handle APIs? Thankfully, Next makes it as easy as creating an API directory in your pages directory and then creating routes that way. We'll create user and users.
[0:28] First, let's handle our users API route. We'll create an index.js inside of it. We'll import our allUsers from our test-data.json. We can then export a default function which will give us access to the request and response variables. We'll send a response status of 200 and attach the JSON method to make sure that we send the users back as a JSON object.
[0:58] Status and JSON methods are utility functions included by Next.js to make handling data in your routes even easier.
[1:08] Now let's consume that data in the view. We'll be using useQuery to do our fetch to our local API and fetch from our isomorphic-unfetch.
[1:20] First, we'll declare useQuery and destructure data and status from our useQuery. We'll pass in a query key of users and our second, which is an async function. We'll declare a constant of users and set it to await our fetch to our /api/users route. Then we'll return our users and make sure to read the body text as JSON with our .json method.
[1:49] Let's utilize that data. First, we'll check to make sure that if the status is loading, we'll return a <p> tag with "Loading ..." inside of it. Otherwise, we can start to render a div. Inside that div, we'll check to make sure that data isn't undefined. If it isn't, we'll do a data.map.
[2:09] We'll take the user. We'll render out a fragment. Then, in that fragment, we can just render the user's name and the user's email. Once we refresh, we'll see our list of users with their name and emails.