Home > Software engineering >  React : state not immediatly updating, even with prevState and useEffect
React : state not immediatly updating, even with prevState and useEffect

Time:11-03

sorry for the newbie question but I searched and tried everything I found on the net.

This is my code :

const [userNewInfos, setUserNewInfos] = useState({
    user_firstname: "1",
    user_lastname: "2",
    user_password: "3",
  });

  useEffect(() => {
    const saveChange = (e) => {
      e.preventDefault()
      setUserNewInfos((prev) => {
        return {
          ...prev,
          user_firstname: "4",
          user_password: "5",
          user_lastname: "6",
        };
      });
      console.log(userNewInfos);
    };
  }, [userNewInfos])

return (
    <div className="modal">
      <form className="modal__infos" onSubmit={saveChange}>
    .......
    </form>
    </div>
    )

My state does not update immediately after being changed, apparently this is à normal behavior because useState is running asynchronously, so I am using ... prevState to fix the problem, but it does not change anything, my console.log always returns 1, 2 and 3 instead of 4, 5 and 6.

So, I use the useEffect hook, but the problem is that by doing that, I no longer have access to my saveChange() function which is called in my form on submit (scope problem).

I don't even know if useEffect would fix the problem.

What am i supposed to do to my console.log to return 4, 5, 6 if prevState doesn't fix the problem and useEffect makes my function inaccessible?

Thank you

CodePudding user response:

Try

const saveChange = (e) => {
      e.preventDefault()

      const updatedUserNewInfos = {
          ...userNewInfos,
          user_firstname: "4",
          user_password: "5",
          user_lastname: "6",
       };

      setUserNewInfos(updatedUserNewInfos);
      console.log(updatedUserNewInfos);
};
  • Related