Home > Blockchain >  React component doesn't re-render on state change
React component doesn't re-render on state change

Time:03-14

i have this state in my Profile.js functional component:

  const [isFollowing, setIsFollowing] = useState(
    user?.followings.includes(proUser?._id)
  );

conditional rendering based on state:

return (
...
 <button onClick={followUser}>
   {isFollowing ? "Unfollow" : "Follow"}
  </button>
...

I'm 100% sure that the result of user?.followings.includes(proUser?._id) is true but the button still says "follow", so i console log it to see what's happening :

 console.log(user?.followings.includes(proUser?._id);

the component will re-render 3 times, first time it prints false, second time may be either false or true, the third time it always print true, but the state is still false, the component will not re-render on state change and even the state won't change, why is that happening and how to fix it?

followUser function in case you want to take a look:

  const followUser = async () => {
    if (isFollowing) {
      await fetch(`http://localhost:8000/unfollow-user/${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId: user?._id,
        }),
      });
      dispatch({ type: "UNFOLLOW", payload: id });
    } else {
      await fetch(`http://localhost:8000/follow-user/${id}`, {
        method: "PUT",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          userId: user?._id,
        }),
      });
      dispatch({ type: "FOLLOW", payload: id });
    }

    setIsFollowing(!isFollowing);
  };

CodePudding user response:

Initial state will be disregarded for subsequent renders. You must use setIsFollowing(user?.followings.includes(proUser?._id)) instead.

Put it into useEffect and it will work.

  • Related