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?
The two subsequent setData calls end up "overwriting" each other since the data captured by your handleLikes will not have changed after you call setData.
You'll want to use the functional form of setState to be able to reliably look at the current value (even when asynchronous modifications are in queue, then return a new value based on it:
const handleToggleLikes = (e) => {
setData((data) =>
data.isLiked
? { ...data, likes: data.likes - 1 }
: { ...data, likes: data.likes + 1 },
);
setData((data) => ({ ...data, isLiked: !data.isLiked }));
};
You can do both of these modifications in one invocation:
const handleToggleLike = e => {
setData(data => ({
...data,
likes: data.likes + (data.isLiked ? -1 : 1), // decrease if previously liked
isLiked: !data.isLiked,
}));
}
There are two ways to use a setState function to update the state object:
Whenever you want to use the current state object to create a new state object, you must use the second way. In your case, your code:
setData({...data, likes: data.likes - 1})
uses the current state object (data) to create the new state object. So you must use a callback instead, like this:
setData((cur_data)=>({...cur_data, likes: cur_data.likes-1}))
Note that I am using the arrow syntax in the callback function to return the new state object.