useSelector will not display updated state

28 Views Asked by At

I am absolutely beating my head against this. I am fairly new to Redux and I need some guidance. I am simply trying to add a new 'post' and display it in a list. When I add a post, it indeed works. However it will only display it once I reload the page.

I have tried useEffect, I have tried store.getState(). I am very stuck. I have also examined the store object and can verify that the data structure is correct.

When a new post is created, I create a copy of the post and rename it to the length of posts. I know that is odd but that is the use-case.

I've had to rename things in this sample.

function MyComponent() {
    const posts = useSelector((state: any) => state.post.posts)
    const [postSelection, setPostSelection] = useState<string>(posts[0].name)
    const dispatch = useDispatch()
    const create_action_creator = bindActionCreators(create_post, dispatch)
    const delete_action_creator = bindActionCreators(delete_post, dispatch)

    const handleCreateNewPost = async () => {
        let postToCopy = posts.filter((post: Post) => post.name === postSelection)[0]
        postToCopy.name = `${postToCopy.name} ${posts.length}`
        // We should not be setting the new post to default
        postToCopy.is_default = false
        create_action_creator(postToCopy)
    }

return (
<Button 
   onClick={handleCreateNewPost} 
   variant="contained" 
   style={{width: '100%', marginLeft: '2%'}}>Create New Post</Button>
            {posts.map((post: Post) => 
                <div>
                    {post.name}
                </div>
            )})
}

My action creator:

export const create_post = (post: Post) => {
  return async (dispatch: Dispatch<PostAction>) => {
    return axios.post('/api/post/', post)
      .then(response => {
        dispatch({
          type: PostActions.CREATE,
          payload: response.data
        })
      })
  }
}
0

There are 0 best solutions below