Creating the HomePage component

Now, we are going to create the HomePage component from the PostList component and the Resource Hook that is concerned with the posts. Again, we are going to refactor src/App.js, in order to create a new component.

Let's start creating the HomePage component:

  1. Create a new file, src/pages/HomePage.js, import React with the useEffect and useContext Hooks, and define the component there. We also define a Context Hook and pull out the state object and dispatch function:
import React, { useEffect, useContext } from 'react'
import { StateContext } from '../contexts'

export default function HomePage () {
const { state, dispatch } = useContext(StateContext)
const { error } = state

return (
<div>
</div>
)
}
  1. Then, cut the following import statements (and adjust the paths) from src/App.js, and add them after the import React from 'react' statement in src/pages/HomePage.js:
import { useResource } from 'react-request-hook'
import PostList from '../post/PostList'
  1. Next, cut the following Hook definitions from src/App.js, and insert them before the return statement of the HomePage function:
    const [ posts, getPosts ] = useResource(() => ({
url: '/posts',
method: 'get'
}))
useEffect(getPosts, [])
useEffect(() => {
if (posts && posts.error) {
dispatch({ type: 'POSTS_ERROR' })
}
if (posts && posts.data) {
dispatch({ type: 'FETCH_POSTS', posts: posts.data.reverse() })
}
}, [posts])
  1. Now, cut the following rendered code from src/App.js, and insert it in between the <div> tags of src/pages/HomePage.js:
            {error && <b>{error}</b>}
<PostList />
  1. Then, import the HomePage component in src/App.js:
import HomePage from './pages/HomePage'
  1. Finally, render the HomePage component below the <hr /> tag:
            <hr />
<HomePage />

Now, we have successfully refactored our current code into a HomePage component. Next, we move on to creating the PostPage component.

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

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