How to check if state variable has been changed

Viewed 184

I have been trying to figure this out for awhile but basically I have a list of tags with

tags with onClick properties that should change a state variable postsShown to true. Tricky thing is the postsShown is supposed to be an array of boolean values and uses the index to differentiate which

tag was clicked. Now the state variable does update but gets stuck and does not get detected by my conditional statement. this is my code, I have tried calling the setState function with a callback but get an error

1 Answers

Your onClick event is not changing the object just the content inside the object. Since the pointer to the object didn't change React will not re-redner your component.

change your onClick function:

onClick={()=>{
  const postsClone = [...postsShown];
  postsClone[index]= true;
  setPostsShown(postsClone);
}}

[...postsShown] will create a new reference by copying the top level of the object.

If you need to create a deep copy use

const postsClone = JSON.parse(JSON.stringify(postsShown));
Related