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:
- Create a new src/pages/PostPage.js file.
- 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'
- Now, define the PostPage component, which is going to accept the post id as prop:
export default function PostPage ({ id }) {
- 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])
- 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.