Creating the PostPage component

We are now going to define a new page component, where we will only fetch a single post from our API and display it.

Let's start creating the PostPage component now:

  1. Create a new src/pages/PostPage.js file.
  2. Import React, the useEffect and  useResource Hooks and the Post component:
import React, { useEffect } from 'react'
import { useResource } from 'react-request-hook'

import Post from '../post/Post'
  1. Now, define the PostPage component, which is going to accept the post id as prop:
export default function PostPage ({ id }) {
  1. Here, we define a Resource Hook that will fetch the corresponding post object. We pass the id as dependency to the Effect Hook so that our resource re-fetches when the id changes:
    const [ post, getPost ] = useResource(() => ({
url: `/posts/${id}`,
method: 'get'
}))
useEffect(getPost, [id])
  1. Finally, we render the Post component:
    return (
<div>
{(post && post.data)
? <Post {...post.data} />
: 'Loading...'
}
<hr />
</div>
)
}

We now also have a separate page for single posts.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.6.75