A Custom React Hook that handles duplicate API call
Anxiny
Posted on April 26, 2021
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.delete(url);
setData(json.title);
});
}, []);
return data;
}
Here is a demo.
Thank you all! Please let me know if you have any suggestion.
π πͺ π
π©
Anxiny
Posted on April 26, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.