So I have run into an issue where React is not batching together multiple setState() calls inside of an async function (React usually does this automatically outside of an async function). This means that when my code is run, multiple consecutive setState() calls conflict with eachother, the first setState() causes the component to update and the second setState() happens before the component has had enough time to remount and I get the error "Can't perform a React state update on an unmounted component". I did some research and found out that this is expected behaviour but I've found nothing about how to fix the issue.
Here's some example code (doesn't run) just to visualise what I'm trying to say. In this case the lines setData(response.data); and setLoading(false); conflict and cause the error.
I need some way to make the two calls atomic.
import React, { useState } from "react";
import Button from "@material-ui/core/Button";
const Demo = () => {
const [loading, setLoading] = useState(false);
const [data, setData] = useState({});
const fetchData = async () => {
setLoading(true);
const response = await callAPI();
if (response.status === 200) {
setData(response.data);
}
setLoading(false);
};
return (
<div>
<Button disabled={loading} onClick={() => fetchData()}>
Fetch Data
</Button>
<p>{JSON.stringify(data)}</p>
</div>
);
};
export default Demo;