I'm quite new to react and trying to ease some development.
I'm having this custom hook useApi.
import {useState} from "react";
import {PetsApiFactory} from "petstore-axios-api"
import {useKeycloak} from "@react-keycloak/web";
const petsApi = new PetsApiFactory({}, `${process.env.REACT_APP_BASE_URL}`);
export const useApi = () => {
const [isLoading, setIsLoading] = useState(false);
const {keycloak} = useKeycloak();
const createPets = (requestData) => {
setIsLoading(true);
return petsApi.createPets(requestData, {
headers: {
Authorization: `Bearer ${keycloak.token}`
}
}).finally(() => setIsLoading(false));
};
const listPets = (limit = undefined) => {
setIsLoading(false);
return petsApi.listPets(limit, {
headers: {
Authorization: `Bearer ${keycloak.token}`
}
}).finally(() => setIsLoading(false));
};
const showPetById = (petId) => {
setIsLoading(true);
return petsApi.showPetById(petId, {
headers: {
Authorization: `Bearer ${keycloak.token}`
}
}).finally(() => setIsLoading(false));
};
return {
createPets,
listPets,
showPetById,
isLoading
}
};
I'd like to call it from within another component like in this snippet.
useEffect(() => {
listPets()
.then(result => setPetsData(result.data))
.catch(console.log)
}, []);
However react is telling me that I'm missing the dependency on listPets
React Hook useEffect has a missing dependency: 'listPets'. Either include it or remove the dependency array
I've tried to include listPets as a dependency but that leads to repeatable call to backend service. What would be the best way to rewrite the call to useApi hook?
Thanks
Change component's useEffect:
useEffect(() => {
listPets()
.then(result => setPetsData(result.data))
.catch(console.log)
}, [listPets]);
And then try to wrap listPets function with useCallBack hook like this:
const showPetById = useCallback((petId) => {
setIsLoading(true);
return petsApi.showPetById(petId, {
headers: {
Authorization: `Bearer ${keycloak.token}`
}
}).finally(() => setIsLoading(false));
},[petsApi]);
you have forget to add listPets into useEffect
useEffect(() => {
listPets()
.then(result => setPetsData(result.data))
.catch(console.log)
}, [listPets]);
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