I have an AsyncThunk method named likePost
when a user clicks like
on a post it will send this action via dispatch. The method runs fine, and in my database the Post
is updated successfully, but I can’t get Redux to update the Post that is liked during the .fulfilled
method.
Here is what I’m currently working with:
JavaScript
x
18
18
1
// shoes = [{_id: '', title: '', likes: []}, ...{}]
2
export const likePost = createAsyncThunk(
3
'posts/likePost',
4
async (payload, { rejectWithValue }) => {
5
try {
6
const response = await userTokenAxios.post(`/${payload}/like`);
7
return response.data;
8
} catch (error) {
9
return rejectWithValue(error.response.data);
10
}
11
}
12
);
13
14
[likePost.fulfilled]: (state, action) => {
15
const post = state.posts.find((post) => post._id === action.payload._id);
16
post.likes.push(action.payload.user);
17
},
18
Advertisement
Answer
Instead of finding the post, get the index for that object in state.posts const post = state.posts.find((post) => post._id === action.payload._id);
JavaScript
1
2
1
const postIndex=state.posts.findIndex((post)=> post._id === action.payload._id);
2
Now you can push the user
in likes array:
JavaScript
1
2
1
state.posts[postIndex].likes.push(action.payload.user)
2