Use SWR to Fetch Data from a Next.js API Route

Lee Robinson
InstructorLee Robinson
Share this video with your friends

Social Share Links

Send Tweet
Published 4 years ago
Updated 4 years ago

SWR, a React hooks library for data fetching, makes it easy to communicate with your Next.js API Route.

Instructor: [0:00] First, navigate to your terminal and install SWR. Then, go to pages/index.js which is the entry point to your Next.js application. We can import this new hook, import useSWR from SWR.

[0:18] Our index function needs to call this React hook, so we'll say useSWR. The first key, which is the cache key, is the API route that we want to call, /api/item given some ID. If we go back over to AWS, I'm going to steal this ID from an object in DynamoDB.

[0:46] The second parameter is a fetcher. This fetcher is a function that we're going to define that tells SWR how to communicate with our API route. Given some URL, we want to use the browser fetch. This is going to return a promise. On the response, we're going to say return JSON.

[1:12] We have our fetcher defined. We have our API route. On this response, which is an object, we can destructure the data and the error. If we go and we look, we can say, "If there's an error, then we want to return some div," and we can say, "It failed to load." If there's no data, that's how that we know that we're in a loading state. We can return a div here as well and just say loading.

[1:46] Finally, we want to return the data that we received. I'm going to put this in a code block. It's going to be a JSON blob, so I can just do JSON.stringify some data. We'll just clean this up, so it looks nicer and save.

[2:11] If we go and we run our code and start our server at localhost:3000, and we go back over, you'll see it refreshes. We saw a loading state. Now, we see the new JSON content from DynamoDB.

[2:29] One interesting feature of SWR is that when you refocus or revalidate on the page, it will call your API and fetch new information. If I were to go to DynamoDB, and go in here and modify this directly and hit Save, when I navigate back to localhost:3000, it goes and refetches the latest information from my API route keeping things up to date.

[2:56] You have full control over this if you'd like. You can dive into the options and configure exactly how you want that to happen, but this abstracts away a lot of the work that you would need to do to fetch data from either local or remote APIs.