I'm using localstorage for storing user id and then sending it to state, then using it to hide like button after clicking it, but after clicking like button, it doesn't disappearing and user can keep liking the post(many times).
Login code: Here I store the user in localstorage and dispatch it.
localStorage.setItem("user",JSON.stringify(data.user))
dispatch({type:"USER",payload:data.user})
history.push('/c')
userReducer code:
export const initialState = null
export const reducer = (state,action)=>{
if(action.type==="USER"){
return action.payload
}
return state
}
Like functionality:
const likePost = (id)=>{
fetch('/post/like',{
method:"put",
headers:{
Accept:"application/json",
"Content-Type":"application/json",
},
body:JSON.stringify({
postId:id
})
}).then(res=>res.json())
.then(result=>{
//console.log(result)
const newData = data.map(post=>{
if(post._id===result._id){
return result
}else{
return post
}
})
setdata(newData)
}).catch(err=>{
console.log(err)
})
}
frontend code:
{posts.likes.includes(state._id)
?<AiTwotoneDislike size="2em" onClick={()=>{unlikePost(posts._id)}}/>
:<AiFillLike size="2em" onClick={()=>{likePost(posts._id)}}/>
}
The main problem is in this above code only, it takes state._id, but only shows like button after clicking also. I have checked state, it does contain _id.