Rev 3497 | Rev 3658 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |
import { api } from '@api';import { useApi } from './useApi';import { useAlert } from './useAlert';import { useEffect, useRef } from 'react';const getResources = async (url, params) => {return await api.get(url, { params });};export function useFetch(url, { params = undefined } = {}) {const { showError } = useAlert();const { loading, data, error, execute } = useApi(getResources);const hasFetched = useRef(false);useEffect(() => {if (!hasFetched.current) {execute(url, params);hasFetched.current = true;} else if (url || params) {// Volver a ejecutar si url o params cambian después de la inicialexecute(url, params);}}, [url, params, execute]); // 'execute' también es una dependenciauseEffect(() => {if (error) showError(error);}, [error, showError]); // 'showError' también es una dependenciareturn {data,loading,refetch: () => execute(url, params)};}