Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

    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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading