I am new to React. I have a GET
API. First I will load in ueEffect
.
Whenever I am calling that my browser showing that API is running infinite time.
I did something in the useEffect
dependency by providing wrong function . But I don’t know how to stop that. Added screenshots below
This is my useState
that holds the data:
const [loadData, setLoadData] = useState([]);
This is my async function I am setting my state in:
const fetchData = useMemo(() => async => {
try {
const responseData = await axios.get(baseUrl { withCredentials: true })
const details = await responseData.data;
setapiLoading(false); //loader false
if (details.length === 0) {
setLoadData(null);
}
else {
setLoadData(details);
}
}
catch (error) {
toast.error( error + ':Please try again', { position: toast.POSITION.TOP_CENTER })
}
}
useEffect(() => {
fetchData();
}, [fetchData]);
In this image, the effect is running forever:
How can I solve this? Thanks in advance.
2
Answers
The effect runs every time
fetchData
changes. The reference tofetchData
changes every timeloadData
changes. So, the effect runs every timeloadData
changes (continuously).To fix it, put everything inside the effect so it only runs once on mount:
the reason why it running infinitely because you pass
loadData
as a dependency to useMemo() for fetchData. as a result, every time you calling setLoadData(), useMemo will return new instance of fetchData, which subsequently triggersuseEffect()
.Here is how you can solve it by defining
fetchData
insideuseEffect
: