variable initialized useState as true but the state is false
hasReaction is true, but liked is false
error gets printed multiple times
const hasReaction = postWithUser.reactions.some(
(reaction) => reaction.userId === user?.id ?? ""
);
const [liked, setLiked] = useState(hasReaction);
if(hasReaction !== liked) { console.log('error'); } I'm calling this in side each tweet component Is this common and is it supposed to happen? maybe it has sth to do with life cycles?
const [liked, setLiked] = useState(hasReaction);
if(hasReaction !== liked) { console.log('error'); } I'm calling this in side each tweet component Is this common and is it supposed to happen? maybe it has sth to do with life cycles?
2 Replies
if
postWithUser
is a prop or some outer state that you pass down it could be possible that on the initial render it's value is being set to false
and later on changes to true
, therefor when your initial useState value is set it will be set to false
but hasReaction
will be equal to true
thanks for the insight. I'm pretty sure that I didn't change the state anywhere, and the initial value shouldn't be changed. it seems like the .some statement has something to do with it. I changed it to const hasReaction = postWithUser.reactions.length > 0;
and it worked. Not sure why tho
what I'd really like to know is if there's some kind of pitfall in this react system which caused this, because changing the code didn't solve the problem in call places