Home > other >  Update variable and use it immediately React
Update variable and use it immediately React

Time:03-15

I am trying to update a variable after an api call but I will use a click event for this question.

As you can see, the variable that i print uses the old state on the first click as it doesn't register the change yet. On the following calls the variable gets printed with the new text.

Is there a way to use the updated variable immediately within the changeText function?

https://stackblitz.com/edit/react-36jqi3

export default function App() {
  const [text, setText] = useState('inital text');

  const changeText = () => {
    setText('new text');
    console.log(text);
  };

  return (
    <div>
      <button onClick={changeText}>Update variable</button>
    </div>
  );
}

CodePudding user response:

No.

The changeText function that is currently running will have closed over the value of text from the value assigned during the render that created the changeText function.

The next render of the component will generate a new changeText function and assign it to onClick.

If you want to use the value you've just passed to setState then keep a copy of that value somewhere else.

const changeText = () => {
  const newValue = 'new text';
  setText(newValue);
  console.log(newValue);
};

CodePudding user response:

Can get by way.

export default function App() {
  

  const [text, setText] = useState('inital text');


  const changeText = () => {
    /* Calling updater to get the latest value. */
    setText('new text');
    setText((state) => {
       console.log("immediately updated text -->", state); 
       return state;
    });
  };



  return (
    <div>
      <button onClick={changeText}>Update variable</button>
    </div>
  );
}
  • Related