When I try to run code like below, I get the eslint warning React Hook useEffect has a missing dependency: 'userApi'. Either include it or remove the dependency array.(react-hooks/exhaustive-deps)
const userApi = useFetch();
useEffect(() => {
userApi.run("/api/user");
}, []);
But if I add userApi as dependency, then I get a recursive loop. If I ignore the warning everything is fine. Should I just ignore it?
Here is my useFetch hook:
const useFetch = () => {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const auth = useAuth();
const run = async (url, method = "GET", data, options) => {
setError();
setIsLoading(true);
try {
const token = await auth.user.getIdToken();
if (!options)
options = {
method,
headers: {
"Content-Type": "application/json"
}
};
if (!options.headers) options.headers = {};
if (!options.headers["Authorization"])
options.headers["Authorization"] = `Bearer ${token}`;
if (!options.body && data) options.body = JSON.stringify(data);
const response = await fetch(url, options);
console.log(response);
if (!response.ok) throw Error(response.statusText);
const json = await response.json();
setData(json);
} catch (e) {
console.log(e);
setError(e.message);
}
setIsLoading(false);
};
return { data, error, isLoading, run };
};
Update, my working code:
const [getUser, { data: user, error, loading }] = useFetch("/api/user");
useEffect(() => {
getUser();
}, [getUser]);
The fetch hook:
const useFetch = (url, method = "GET") => {
const [loading, setLoading] = useState(false);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const { user } = useAuth();
const run = useCallback(
async (data, options) => {
...code...
},
[user, method, url]
);
return [run, { data, error, loading }];
};