I have conditional rendering. When i use onClick event all my components update. My functions.
const reaction = (author) => {
if (author == user.id){
return false
}else{
return true
}
}
const handleReactions = (reaction, id) =>{
if (reaction === 'like'){
httpClient.put(`/likes/${id}/`)
.then((response) => {
alert(response.data);
})
}
}
My return
return (
{reaction(post.user)
?<form>
<button type="submit" name="like" value={post.id} onClick={handleReactions('like', post.id)}>
: //another conditional
}
)
Try something like :
return (
{reaction(post.user)
?<form>
<button type="submit" name="like" value={post.id} onClick={() => handleReactions('like', post.id)}>
: //another conditional
})
Explanation: you are calling handleReactions directly instead of giving the function to execute when the button is clicked. Solution define lambda function which is calling your function inside
PS : your function :
const reaction = (author) => {
if (author == user.id){
return false
}else{
return true
}
}
Can be simplified:
const reaction = (author) => author != user.id