Adjusting the CREATE_POST action

Previously, we dispatched a CREATE_POST action when a new post gets created. However, this action does not contain the post id, which means that links to newly created posts will not work.

We are now going to adjust the code to pass the post id to the CREATE_POST action:

  1. Edit src/post/CreatePost.js, and import the useEffect Hook:
import React, { useState, useContext, useEffect } from 'react'
  1. Next, adjust the existing Resource Hook to pull out the post object after the creation of the post finishes:
    const [ post, createPost ] = useResource(({ title, content, author }) => ({
  1. Now, we can create a new Effect Hook after the Resource Hook, and dispatch the CREATE_POST action once the result of the create post request becomes available:
    useEffect(() => {
if (post && post.data) {
dispatch({ type: 'CREATE_POST', ...post.data })
}
}, [post])
  1. Next, we remove the call to the dispatch function in the handleCreate handler function:
    function handleCreate () {
createPost({ title, content, author: user })
dispatch({ type: 'CREATE_POST', title, content, author: user })
}
  1. Finally, we edit src/reducers.js, and adjust the postsReducer as follows:
function postsReducer (state, action) {
switch (action.type) {
case 'FETCH_POSTS':
return action.posts

case 'CREATE_POST':
const newPost = { title: action.title, content: action.content, author: action.author, id: action.id }
return [ newPost, ...state ]

Now, links to the newly created posts work fine, because the id value is added to the inserted post object.

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

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