0

I try to update the values in the useState with the fetched data. when I console.log data.success it returns true. Then I assign it to the success value. but it returns false! why? why value success doesn't get updated immediately. At the end i receive the message from the server that the login was successful. SIGN IN success: false the user admin is logged

const Signin = () => {
  const [values, setValues] = useState({
    success: false
  });

  const { success } = values;

  const clickSubmit = async event => {
    event.preventDefault();

    const signReact = catchAsync(async (email, password) => {
      const data = await signin(email, password) // fetch data from the server
      console.log(data.success); // -> true
      if (data) {
        setValues({
          ...values, success: data.success // -> assign to success
        });
        console.log("SIGN IN success: " + success); // -> false! why?!
      }
      return data;
    });

    signReact(email, password);
  };

3 Answers3

0

setState() is an asynchronus function. So you cannot print it in the next statement.It will take some time.To see the updated state values you can log it in useEffect() like this

useEffect(()=>{

console.log(values);
},[values])
0

According to the docs:

Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState. Pass an updater function instead of an object if you need to compute values based on the current state:

Example:

const Signin = () => {
  const [values, setValues] = useState({
    success: false
  });

  const { success } = values;

  React.useEffect(()=> {
    console.log("SIGN IN success: " + success);
  }, [values]);

  const clickSubmit = async event => {
    event.preventDefault();

    const signReact = catchAsync(async (email, password) => {
      const data = await signin(email, password) // fetch data from the server
      console.log(data.success); // -> true
      if (data) {
        setValues({
          ...values, success: data.success // -> assign to success
        });
      }
      return data;
    });

    signReact(email, password);
  };
Alessio Koci
  • 1,103
  • 11
  • 24
0

use useEffect. Try something like this:

useEffect(() => {
    console.log("SIGN IN success: " + values.success);
  }, [values]);

...
...
 const data = await signin(email, password);
 setValues(prevState =>{...prevState, success: data.success});
blueseal
  • 2,726
  • 6
  • 26
  • 41