React, need to avoid multiple API requests.

I have toggle button , on toggle if its on then it opens side drawer, So API requests need to be called only on opening of side drawer and show the response coming back from the API. (so everytime it clicks on toggle button it should avoid calling another api - if there is already one running already)
1 Reply
EIO
EIO3mo ago
keep track of the API state in your state manager - Prop drilling from parent scope, Context, Redux or even localStorage. Example (with prop drilling):
// ParentComponent.jsx
...
useEffect(() => {
// Run once, on component mount
setIsApiRunning(false);
}, []);
// ParentComponent.jsx
...
useEffect(() => {
// Run once, on component mount
setIsApiRunning(false);
}, []);
// DrawerComponent.jsx
...
const { isApiRunning, setIsApiRunning } = props;
...
useEffect(() => {
if (!isApiRunning) makeApiCall();
}, []);

useEffect(() => {
if (apiData.status === "loading") setIsApiRunning(true);
if (apiData.status !== "loading") setIsApiRunning(false);
}, [apiData.status, setIsApiRunning]);
// DrawerComponent.jsx
...
const { isApiRunning, setIsApiRunning } = props;
...
useEffect(() => {
if (!isApiRunning) makeApiCall();
}, []);

useEffect(() => {
if (apiData.status === "loading") setIsApiRunning(true);
if (apiData.status !== "loading") setIsApiRunning(false);
}, [apiData.status, setIsApiRunning]);