Reputation: 9322
I have an icon that when clicked it triggers a function that calls an API
and then dispatch an action to remove a blog post from the state. But the problem is that my UI does not re-render. However, if I refresh my browser the post that I deleted is no longer there and my store matches my state.
Here is my function that calls an API
and then dispatch an action:
export function deletePost(postID) {
return (dispatch) => {
fetch(`${url}/posts/${postID}`, { method: 'DELETE', headers})
.then((response) => response.json())
.then((postID) => dispatch(removePost(postID)))
.catch((error)=>{console.log('dispatch error',error)});
};
Here is my action:
export function removePost ( postID ) {
return {
type: REMOVE_POST,
postID,
}
}
And here is my reducer:
function posts (state = {}, action) {
switch (action.type) {
case REMOVE_POST:
return [
...state.filter((post)=>post.id!==action.postID)
];
default:
return state
}
}
Now when I simply dispatch an action without calling an API
export function deletePost(postID) {
return (dispatch) => {
dispatch(removePost(postID));
}
My state is correctly updated but of course my redux store is not. When I do the calling of API
before dispatching an action as shown earlier, there is also no error coming from the console
log.
What could be the problem here? I am very new to ReactJS
and can't find a solution yet to this problem after many tries.
Also, as a note, I am using redux-thunk
in this project.
Upvotes: 0
Views: 761
Reputation: 961
I have a few questions, but first: I think the problem is here:
[
...state.filter((post)=>post.id!==action.postID)
]
What is the state's shape? Is it state = [post1, post2, ...]
? I can see the initial state is {}
, so I find it weird to be calling state.filter
and not state.posts.filter
or whatever here.
The other might be problem, is with post.id !== action.postID
, maybe the received ID is an number
type, and maybe the local id
is a string
? Maybe the other way around?
Upvotes: 2