Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

52
Vistas
useEffect dependancy array

I'm using customHook to fetch data from an API.

const useFetch = () => {
   const dispatch = useDispatch();
   return async (callback, ...props) => {
      try {
         return await callback(...props);
      } catch (error) {
         const { msg } = error.response?.data || "Something went wrong";
         dispatch(showModal(msg));
         setTimeout(() => dispatch(hideModal()), 3000);
      }
   };
};

and using it inside useEffect

const customFetch = useFetch();
useEffect(() => {
      (async () => {
         const data = await customFetch(fetchUsers, token);
         if (data) setUsers(data.user);
      })();
   }, [token]);

But eslint is complaining about the missing customFetch dependency. If I add it it will end up in an infinite loop. How can I fix this?

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

So you just need useCallback here to make callback you return stable:

const useFetch = () => {
   const dispatch = useDispatch();
   const fetcher = useCallback(async (callback, ...props) => {
      try {
         return await callback(...props);
      } catch (error) {
         const { msg } = error.response?.data || "Something went wrong";
         dispatch(showModal(msg));
         setTimeout(() => dispatch(hideModal()), 3000);
      }
   }, [dispatch]);
   return fetcher;
};

useMemo and useCallback are specifically useful in cases like that, when you need something to be referentially the same, while creating/returning literally would provide new instance on each run(function, array, object)

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos