Home > Software design >  variable doesn't update when trying to increment it while using useState
variable doesn't update when trying to increment it while using useState

Time:11-01

I have a variable initialized in the following way:

let [count_farmers, set_count_farmers] = useState(0);

What I'm trying to do is, when a person is Registering to my page, I wish to increment the variable, like so:

let handleAddUser = (userinfo) => {
    console.log("before: "   count_farmers);
    set_count_farmers(count_farmers   1);
    console.log("after: "   count_farmers);
    //check if email exists @ anyone of the users, if so, don't create!
    let found_user = usersVal.find((user) => userinfo.email == user.email);
    if (found_user === undefined && userinfo.email.includes("@")) {
      console.log(getFarmerImageByName(count_farmers % 5));
      usersEditVal([
        ...usersVal,
        {
          firstname: userinfo.firstname,
          lastname: userinfo.lastname,
          fullname: userinfo.firstname   " "   userinfo.lastname,
          reviews: [{ idReviewer: "", text: "" }],
          location: "Tel Aviv",
          likes: 0,
          about:
            "this is a default about textthis is a default about textthis is a default about textthis is a default aboefbout text",
          likedProfilesId: [],
          likedProductsId: [],
          img: getFarmerImageByName(count_farmers % 5),
          id: v4(),
          isFarmer: userinfo.isFarmer,
          password: userinfo.password,
          email: userinfo.email,
          farmerProducts: [],
          cartProducts: [],
          soldItems: [],
        },
      ]);

      return true;
    } else {
      console.log("EMAIL IS INVALID.");
      return false;
    }
    //****************************************************************** */
  };

Now, doesn't matter how many times I register, the console log of before and after (1st and 3rd lines in the function handleAddUser), I get 0 printed to the screen.

Any ideas?

Regards!

CodePudding user response:

In your case, as you are using the previous value of the state to determine a new one, you'll need to use the useState function feature as your actual implementation is problematic.

You can use it like that:

set_count_farmers((previous) => previous   1)

That way, our state is being updated with the previous value given by the state itself, and not what we assume it is at that given time. It is much more stable to do it that way, although doing it your way works, it will leads to issues.

Now, you need to know that useState is asynchronous, and that it will be done, but that your console.log() occurs too fast.

There is a simple way using useEffect() to log a value when it changes, as it is what you want.

Just use the array dependency of useEffect() to listen to any change made to count_farmers.

The code should looks like this:

useEffect(() => {
   console.log("A change has been detected in count_farmers: ", count_farmers)
}, [count_farmers])

This will log your count AFTER it has been updated, making sure you never log too early.

Also, you have to remember how a component life-cycle works, and that it gets re-rendered each time a state changes. So actually, you could also log it each time the page gets re-rendered ([] dependency), and it would also works. But, it is more appropriate to listen to that particular state to provide updates.

  • Related