Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call hook from another hook in react

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

like image 528
bilak Avatar asked Mar 27 '26 07:03

bilak


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]);
like image 87
Aleksandre Javakhishvili Avatar answered Mar 29 '26 20:03

Aleksandre Javakhishvili


you have forget to add listPets into useEffect

useEffect(() => {
listPets()
    .then(result => setPetsData(result.data))
    .catch(console.log)
}, [listPets]);
like image 22
1pulsif Avatar answered Mar 29 '26 22:03

1pulsif