Call hook from another hook in react

Viewed 2305

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

2 Answers

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]);
Related