I'm currently fetching my data once when the component mounts, then whenever the user clicks a button. I want however to stop the button from fetching if a request is in progress, that's why I'm updating the isFetching
state.
However, I need to add the isFetching
to the useCallback
dependency to remove the warning and if I do, an infinite fetch loop is triggered.
Here's my code:
import { useCallback, useEffect, useRef, useState } from 'react';
export const MyComponent = () => {
const isMounted = useRef(true);
const [isFetching, setIsFetching] = useState(false);
const [data, setData] = useState(null);
// Can also be called from the button click
const getMyData = useCallback(() => {
if (isFetching) return;
setIsFetching(true);
fetch('get/my/data')
.then((res) => {
if (isMounted.current) {
setData(res.data);
}
})
.catch((err) => {
if (isMounted.current) {
setData("Error fetching data");
}
})
.finally(() => {
if (isMounted.current) {
setIsFetching(false);
}
});
}, []); // isFetching dependency warning as is, if added then infinite loop
useEffect(() => {
isMounted.current = true;
getMyData();
return () => {
isMounted.current = false;
};
}, [getMyData]);
return (
<div>
<button onClick={getMyData}>Update data</button>
<p>{data}</p>
</div>
);
};
I understand that there are multiple questions like this one, but I couldn't remove the warning or infinite loop while still checking if the component is mounted.