简体   繁体   中英

How to solve React custom hook TypeError (0 , _ .default) is not a function?

I want to set up a custom hook for data fetching with React Query to easily mock the return values for testing.

This is my useFetchHook custom hook.

export const useFetchData = (idQuery) => {
  const delay = () => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve();
      }, 500);
    });
  };

  const handleRickAndMortyFetch = () => {
    return delay()
      .then(() => axios(`https://rickandmortyapi.com/api/character/${idQuery}`))
      .then((res) => res.data);
  };

  const { data, error, isLoading } = useQuery(
    ["rickandmorty", idQuery],
    handleRickAndMortyFetch,
    {
      cacheTime: 1000 * 60 * 60 * 24,
      enabled: false || idQuery !== 0,
      onError: (error) => console.log(error),
      retry: false,
      refetchOnWindowFocus: true,
      staleTime: 1000 * 60 * 60 * 24,
      useErrorBoundary: true
    }
  );

  return { data, error, isLoading };
};

However, I receive a TypeError (0, _useFetchData2.default) is not a function , which points to this line of code in the <Home/> .

const { data, error, isLoading } = useFetchData(idQuery);

These are my attempts to solve the issue

  • Try different export methods. export default function useFetchData(idQuery) or export const useFetchData = (idQuery) => {}
  • Assure custom hook is returning values return { data, error, isLoading }
  • Assure custom hook is invoked and argument is passed. useFetchData(idQuery)
  • Destructure useFetchHook as object as it's returning an object.
    inside useFetchHook is return { data, error, isLoading };
    inside <Home/> is const { data, error, isLoading } = useFetchData(idQuery);
  • React version is 17.0

Please advise how to solve.

Cause you "named export" useFetchData instead of default export So change To

import useFetchData from "../../hooks/useFetchData";

in Home.jsx

import { useFetchData } from "../../hooks/useFetchData";

Or change export const useFetchData to export default useFetchData

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM