Home > Enterprise >  Call custom hook twice in the same component
Call custom hook twice in the same component

Time:10-20

I want to use this custom hook for making api requests:

export default function useFetch({ method, url, data = null, config = null }) {
   const [response, setResponse] = useState(null);
   const [error, setError] = useState("");
   const [isLoading, setIsLoading] = useState(true);

   useEffect(() => {
      const fetchData = async () => {
         try {
            api[method](url, JSON.parse(config), JSON.parse(data))
               .then((res) => {
                  setResponse(res.data);
               })
               .finally(() => {
                  setIsLoading(false);
               });
         } catch (err) {
            setError(err);
         }
      };

      fetchData();
   }, [api, method, url, data, config]);

   return { response, error, isLoading };
}

The above code is not important. So do not pay much attention to it. My question is how I can make two api calls within the same component. Is that possible?

export const programApi = axios.create({
   baseURL: programApiUrl,
});

const {response, isLoading} = useFetch({
   api: programApi,
   method: "get",
   url: "/SportsProgram/active_sport_type",
   config: JSON.stringify({ requireAuthentication: true }),
});

useEffect(() => {
   if (response !== null) {
      // do more stuff if you wish
   }
}, [response]);

Is it possible to use useFetch twice?

CodePudding user response:

You can rename the values in the object when destructing them in your component like so:

const {response, isLoading} = useFetch({
   api: programApi,
   method: "get",
   url: "/SportsProgram/active_sport_type",
   config: JSON.stringify({ requireAuthentication: true }),
});

const {response: response2, isLoading: isLoading2} = useFetch({
   api: programApi,
   method: "get",
   url: "/SportsProgram/active_sport_type",
   config: JSON.stringify({ requireAuthentication: true }),
});

console.log(response, response2)

Or instead of returning an object in your hook return an array. Then in your component you can destruct them and call them different names.

export default function useFetch({ method, url, data = null, config = null }) {
   const [response, setResponse] = useState(null);
   const [error, setError] = useState("");
   const [isLoading, setIsLoading] = useState(true);

   useEffect(() => {
      const fetchData = async () => {
         try {
            api[method](url, JSON.parse(config), JSON.parse(data))
               .then((res) => {
                  setResponse(res.data);
               })
               .finally(() => {
                  setIsLoading(false);
               });
         } catch (err) {
            setError(err);
         }
      };

      fetchData();
   }, [api, method, url, data, config]);

   return [ response, error, isLoading ];
}

Then in your component you can do like :

const [firstResponse, firstError, firstIsLoading] = useFetch(...your stuff)
const [secondResponse, secondError, secondIsLoading] = useFetch(...your stuff)
  • Related