Handling error state

We have already handled the loading state in the ChangeTheme component. Now, we are going to implement the error state for posts.

Let's get started handling the error state for posts:

  1. In src/reducers.js, define a new errorReducer function with a new action type, POSTS_ERROR:
function errorReducer (state, action) {
switch (action.type) {
case 'POSTS_ERROR':
return 'Failed to fetch posts'

default:
return state
}
}
  1. Add the errorReducer function to our appReducer function:
export default function appReducer (state, action) {
return {
user: userReducer(state.user, action),
posts: postsReducer(state.posts, action),
error: errorReducer(state.error, action)
}
}
  1. In src/App.js, adjust the default state of our Reducer Hook:
    const [ state, dispatch ] = useReducer(appReducer, { user: '', posts: [], error: '' })
  1. Pull the error value out of the state object:
    const { user, error } = state
  1. Now, we can adjust the existing Effect Hook that handles new data from the posts resource, by dispatching a POSTS_ERROR action in the case of an error:
    useEffect(() => {
if (posts && posts.error) {
dispatch({ type: 'POSTS_ERROR' })
}
if (posts && posts.data) {
dispatch({ type: 'FETCH_POSTS', posts: posts.data })
}
}, [posts])
  1. Finally, we display the error message before the PostList component:
                 {error && <b>{error}</b>}
<PostList />

If we only start the client now (via npm run start:client), the error will be displayed:

Displaying an error when the request fails!

As we can see, the Failed to fetch posts error gets displayed in our app, because the server is not running. We can now move on to implementing post creation via requests.

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

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