Home > Mobile >  the function doSomethingWithData(v) is being called with the wrong value of the variable V. T
the function doSomethingWithData(v) is being called with the wrong value of the variable V. T

Time:12-18

    const Hello = () => {
      const [v, setV] = React.useState(1);
    
      React.useEffect(() => {
        setTimeout(async () => {
          await setV(2);
          doSomethingWithData(v)
        }, 3000)
      }, []);
    
    
      return (
        <div>
          <h1>Hello, world {v}!</h1>
        </div>
      );
    }
    
    const doSomethingWithData = (v) => {
      //report e-commerce data to our server here..
      
    console.log('Variable value is: '   v);
    }
    
    ReactDOM.render(
      <Hello />,
      document.getElementById('root')
    );

the function doSomethingWithData(v) is being called with the wrong value of the variable V. That is problematic because a record will be created in our e-commerce database when doSomethingWithData() is called and as a result we might make choices based on faulty data.can someone explain this?

CodePudding user response:

The following does not work as you expect. setV is async but it does not return a promise to wait for.

async () => {
    await setV(2);
    doSomethingWithData(v);
};

The general pattern is to use useEffect hook with a dependency value which is v in your case.

React.useEffect(() => {
    setTimeout(() => {
        setV(2);
    }, 3000);
}, []);

React.useEffect(() => {
    doSomethingWithData(v);
}, [v]);

CodePudding user response:

If you have the data available just pass that to doSomethingWithData.

    React.useEffect(() => {
      setV(2);
      doSomethingWithData(2)
  }, []);

The view will display the data from the state v and doSomethingWithData won't be a state behind.

  • Related