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:
- Edit src/post/CreatePost.js, and import the useEffect Hook:
import React, { useState, useContext, useEffect } from 'react'
- 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 }) => ({
- 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])
- 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 })
}
- 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.