Challenges

Add Comments Support

Use SWR

To fetch data, we are going to use a module called SWR. It's a React hook that simplifies data fetching, caching & related tasks.

First, let's install it:

yarn add swr

Then import it inside components/Comments.js with the following:

import useSWR from 'swr'

Then add the following code block right after that:

async function swrFetcher(path) {
    const res = await fetch(path)
    return res.json()
}
šŸ’” This is an async function that accepts an input and returns some data in return. We will pass this fetcher into SWR to fetch data.

Now add the following code inside the Comments function replacing const comments = []:

const {data: comments, mutate} = useSWR(`/api/comments?slug=${slug}`, swrFetcher)

(Here's the final version of the file after all these changes.)

Here we invoke the useSWR hook with the following arguments:

  • API path to get comments (this is the SWR cache-key)
  • The fetcher function we defined earlier

Now, SWR will pass the cache-key to the fetcher and fetch data. Then it will return the data for us.


Let's verify this functionality:

  • Open a blog post in your app
  • Login to your app, if you are not
  • Add the following code in the browser console to add a comment
slug = location.pathname.replace('/post/', '')

fetch(`/api/comments?slug=${slug}`, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        content: 'Hello comment'
    })
})
    .then(res => res.json())
    .then(c => console.log(c))
  • Then click anywhere in your page or do some action to regain the focus to your blog post
Q: What was the outcome of this experiment?
authenticating...

šŸ™ We need your help

We need your help to keep maintain & add new content to this course. Here's how you can support us: