This content originally appeared on DEV Community and was authored by AnxinYang
Today, we are going to create a custom hook that solve this problem:
- We have multiple components that calling same API.
- Component may not always be on same page, therefore, they have to call the API by themselves.
Here is a example hook I think can handle this problem:
let isCalling = new Map(); // This can be replace by some global state. I use this for the sake of simplicity.
function useFetch(url) {
const [data, setData] = useState("");
useEffect(() => {
let isThisAPICalling = isCalling.get(url);
if (!isThisAPICalling) {
console.log("new");
isThisAPICalling = fetch(url).then((response) => response.json());
isCalling.set(url, isThisAPICalling);
// The body can only be parsed once.
}
isThisAPICalling.then((json) => {
console.log("done");
console.log(json.title);
isCalling.set(url, null);
setData(json.title);
});
}, []);
return data;
}
Here is a demo.
Thank you all! Please let me know if you have any suggestion.
This content originally appeared on DEV Community and was authored by AnxinYang

AnxinYang | Sciencx (2021-04-26T00:39:44+00:00) Daily Share: A Custom React Hook that handles duplicate API call. Retrieved from https://www.scien.cx/2021/04/26/daily-share-a-custom-react-hook-that-handles-duplicate-api-call/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.