Javascript problem solve

I’ve been trying solve this issue and try to understand why console prints v as 1 instead of 2? Can someone explain to me why this happens?

const Hello = () => {
  const [v, setV] = React.useState(1);

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

  return (
      <h1>Hello, world {v}!</h1>

const doSomethingWithData = (v) => {
  //report e-commerce data to our server here..

  console.log("Variable value is: " + v);

ReactDOM.render(<Hello />, document.getElementById("root"));

While the useState behavior is asynchronous, i don’t believe it returns a promise for you to await.

The workaround you might consider is useEffect. If you create a useEffect with one dependency, [v], it will trigger every time the useState setter updates that value.

1 Like

The setter function doesn’t return a promise, async await isn’t going to do anything as @snowmonkey says

But look at the logic.

  • component function runs with initial value of v, which is 1.
  • v is set to 2, next time the component renders, v will be 2.
  • console log the value of v, which is 1.
  • component function runs again because state of v has changed.
  • useEffect doesn’t run again because you’ve only told it to run on first render, so no second log

Given that you know the value that v is being set to, why are you not passing that value into the doSomethingWithData function? Because instead, your logic is:

  • pass some value (2) into the function that sets v
  • hope that that function has finished setting v to 2 so you can use the new value of v (it hasn’t, because setting state causes the component function to rerun so that the value can update, and you can’t preemptively get the return value from a function without running the function, that doesn’t make sense).
  • pass the new value of v, which you’re hoping is 2, which you already had in the first place, to the doSomethingWithData function

Not sure I understand the example code. Can you provide some more context about what it is you are trying to achieve here?