Redux state is not updating after adding a blog post
I'd change the structure a bit:
in the createPost method instead of dispatching I'd just return data
export const createPost = ( postData ) => async ( dispatch ) => {
try {
const config = {
headers: {
'Content-Type': 'application/json'
}
}
const { data } = await axios.post( '/api/post', postData, config );
return data;
} catch ( error ) {
console.log( error )
}
}
and then in your code I'd
const submitHandler = ( e ) => {
e.preventDefault();
createPost({post}).then(data=>{
dispatch({type:CREATE_POST, data})
}
this should definitely work
The problem seems to be that React doesn't know that a new post was created. You'll need to call getPosts()
after createPost()
has been called.
const submitHandler = (e) => {
e.preventDefault();
dispatch(createPost({ post }));
dispatch(getPosts());
}
If you want to structure your services in a more centralized, scalable way, check out my blog post on React services: https://schneider-lukas.com/blog/react-connect-rest-api. You could just as well store the posts in the Provider component to make them available to all components in the tree, or better yet create a separate Context, Provider, and Consumer for handling posts.