Challenges

SWR

Fetching Data

This starter app comes with a couple of Next.js API routes that manage our todo items. Here are those APIs:

  • GET /api/todos list all todo items
  • POST /api/todo Add a todo item

Now we are going to fetch todo items and render them on the screen.

First of all, let's install SWR:

yarn add swr
If you are using Codesandbox, this is already installed for you.

Then replace the content of components/Todos.js with the following content:

import { useState } from 'react'
import useSWR from 'swr'
import TodoList from './TodoList'

async function jsonFetcher(path) {
  const res = await fetch(path)
  return res.json()
}

export default function Todos() {
  const {data} = useSWR('/api/todos', jsonFetcher)
  const [listKey, setListKey] = useState(Math.random())
   
  if (!data) {
    return 'loading...'
  }

  const addTodo = async (todoName) => {
    throw new Error('Not implemeted yet!')
  }

  return (
    <TodoList key={listKey} data={data} onNewTodo={addTodo}/>
  )
}

Make your attention to the following line:

const {data} = useSWR('/api/todos', jsonFetcher)

The first argument is the key. SWR uses it for caching and keeps track of the data. Also, the key will be passed to the jsonFetcher function. So, this fetcher function can use the key to fetch related data.

Now try to access the app and add a few todo items. Then reload the page.

Q: How do you describe the result?
authenticating...

Okay. Here's another question for you.

Q: How do you query a GraphQL endpoint?
authenticating...