I feel really stupid for asking such a simple question like this, but for some reason I forgot how to change the value in a React state object. For example:
const initialState = {
likes: 100,
dislikes: 25,
isLiked: false,
isDisliked: false
}
const [data, setData] = useState(initialState)
const handleLikes = e => {
if (data.isLiked) {
setData({ ...data, likes: data.likes - 1 });
} else {
setData({ ...data, likes: data.likes + 1 });
}
setData({ ...data, isLiked: !data.isLiked })
}
<button className={`like-button ${data.isLiked ? 'liked' : ''}`} onClick={handleLikes}>Like | <span className='likes-counter'>{data.likes}</span></button>
The confusing part, the part that made me ask this question, is the likes: data.likes + 1 part. When I click the button, it adds/removes the className as intended, but the value never changes. I know this is such a simple thing but I have spent a while on this.
What is wrong with the likes: data.likes + 1?