Home > Mobile >  Why react not rendering updated state?
Why react not rendering updated state?

Time:05-08

I have a community feature in my application in which users can post their comments.I want to toggle the state of visibility of a comment when clicked on a particular icon. Icon:

 <i className="fa-solid fa-message" onClick={(e)=>handleComment(e)}></i>
        {!props.post.isCommentVisible && <> <Container maxW="md" centerContent p={8}>
          {props.post.comment.map((comm) => (
            <Text>{comm}</Text>
          ))}

The function to toggle the visiblity of ccomment is:

function handleComment(e)
  {
    const id=props.post.id;
    posts.map((post)=>{
      if(post.id==id)
      {
       if(post.isCommentVisible=="false")
       {
         post.isCommentVisible="true";
       }
       else
       {
        post.isCommentVisible="false";
       }
         
         
       db.collection("posts").doc(id).set(post);
      }
    })

  }

Interestingly the state of visibility of comment is updated but react is not rerendering the changed state.

CodePudding user response:

Whether props.post.isCommentVisible is "true" or "false" the expression !props.post.isCommentVisible will always be false because "anyString" is always true.

CodePudding user response:

Assuming somewhere you defined:

const [posts, setPosts] = useState([]);

And then updated populated posts via some fetch operation, you have to call setPosts like:

setPosts(
    posts.map((x) => ({
        ...x,
        isCommentVisible:
            x.id === post.id ? !x.isCommentVisible : x.isCommentVisible,
    }))
);

(use any method you want to achieve the result, mind the comment by Rocky Sims)

This will cause the re-render.

  • Related