So I am working on a React project which has the feature related to that of instagram such that a data is fetched(you can call it feeds).
const feeds = [{
postId: 1,
body: "My first post,
commentList: [{
commentId: 1,
comment: "I love this post"
}],
isFollowing: true,
likers: [1]
}, ]
So the visual of each item must have a like/unlike button, follow/unfollow button and create of comment form. I want only the item to be updated instead when i click on the like button on one item it updates other item in the list.
From what i have done so far, when you click the like button, it dispatch an action and update the state to isLike: true which will be used to change the color of the like button but its affecting every item in the list
Function that handle the like and unlike button
const handleLikeClick = () => { const data = { postId, }; props.unlikePost(data, token); }; const handleUnlikeClick = () => { const data = { postId, }; props.likePost(data, token); };
The view depending on the state depending on the action dispatched
)}{isLike ? ( <i onClick={handleLikeClick}> <img src={IconLike} alt="" /> </i> ) : (
The function that handle the request to the api
export const likePost = (data) => async (
dispatch
) => {
dispatch(likePostSuccess())
await axios
.post(url, data)
.then((response) => {
dispatch(likePostSuccess())
})
.catch(({ err }) => {
dispatch(likePostFailure());
});
};
export const unlikePost = (data) => async (
dispatch
) => {
dispatch(unlikePostSuccess())
await axios
.delete(url,{
data: {
postId: data
}
})
.then((response) => {
dispatch(unlikePostSuccess())
})
.catch(({ err }) => {
dispatch(unlikePostFailure());
});
};
- The reducer file
const initialState = {
isLike: false,
}
case Actions.LIKE_POST_SUCCESSFUL:
return {
...state,
loading: false,
isLike: true,
};
case Actions.LIKE_POST_FAILURE:
return {
...state,
loading: false,
isLike: false
};
case Actions.UNLIKE_POST_SUCCESSFUL:
return {
...state,
loading: false,
isLike: false,
};
case Actions.UNLIKE_POST_FAILURE:
return {
...state,
loading: false,
isLike: true
};
So thats what i have so far so once the action is dispatched and the isLike is updated it should change the color of the like button of each item in the list instead of everything in the list. Thanks in advance.