I am using a custom hook that takes a URL as an argument and returns fetch data and its loading state. So, unlike most hooks, I do not have a function to set a new state when needed and this is causing all kinds of problems at this point in the project because I happen to need a way to re-trigger that custom hook everytime it receives new props values.
The issue is, as expected, the state of the component is being set upon components first render but as it receives new props it does not re-render/re-trigger.
This is how the custom hook looks like:
//useFetch.js
import { useState, useEffect } from "react";
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
async function fetchUrl() {
const response = await fetch(url);
const json = await response.json();
setData(JSON.parse(JSON.stringify(json)));
setLoading(false);
}
useEffect(() => {
fetchUrl();
}, []);
return [data, loading];
}
export { useFetch };
and this is how I am using this hook:
//repos.js
import React from "react";
import { useFetch } from "./fetchHook";
function Repos(props) {
const [userRepos, reposLoading] = useFetch(`https://api.github.com/users/${props.users[props.count].login}/repos`);
return reposLoading ? (
<div className="App">
stuff to render if it's still loading
</div>
) : (
<div
stuff to render if it's loaded
</div>
);
}
Add url to the dependencies array of useFetch hook this will make sure that the effect will rerun when the url prop changes
useEffect(() => {
console.log("refetching url", url);
fetchUrl();
}, [url]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With