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

How to solve Race condition in setting React state?

I have component that have state as object

const [data, setData] = useState({
  input, 
  output: '', 
  enableCopyToClipboard: true,
}

When listen to Observable I do following:

  // reset state before loading stream
  setData({ 
    ...data, 
    output: '',
    enableCopyToClipboard: false,
  });

  loadingStream(request).subscribe((response) => {
    resText.push(response.text);
    setData({ 
      ...data, 
      output: resText.join(''), 
    });
  });

Problem is my enableCopyToClipboard variable in state stays true when it should be false while streaming is ongoing. No idea why.

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

>Solution :

You can use the callback function to set the new data. So you’ll always have the most up to date version of the state. This prevents the override of the old version of the state.

// reset state before loading stream
setData((prevData) => ({
  ...data,
  output: "",
  enableCopyToClipboard: false,
}));

loadingStream(request).subscribe((response) => {
  resText.push(response.text);
  setData((prevData) => ({
    ...prevData,
    output: resText.join(""),
  }));
});

You could also set the enableCopyToClipboard to false by default on the subscribe.

loadingStream(request).subscribe((response) => {
  resText.push(response.text);
  setData((prevData) => ({
    ...prevData,
    enableCopyToClipboard: false,
    output: resText.join(""),
  }));
});
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