Answer a question

I have a custom fetch hook:

export const useFetch = (url: string) => {
  const [response, setResponse] = useState<any>(null);
  const [error, setError] = useState<any>(null);

  const fetchList = (url: string) => {
    return API.get(AMPLIFY_ENPOINTS.default, url, { response: true });
  };

  useEffect(() => {
    const fetchFunc = async () => {
      try {
        const fetchResponse = await fetchList(url);
        setResponse(fetchResponse.data);
      } catch (error) {
        setError(error);
      }
    };
    fetchFunc();
  }, [url]);

  return { response, error };
};

This I then use in a component:

const fetchOrders = useFetch(apiUrl);
useEffect(() => {
  const { response, error } = fetchOrders;
  if (error) setError(error);
  if (response) {...}
}, [fetchOrders]);

And this causes an infinite loop, how should I go about fixing it?

Answers

The fetchOrder reference keeps changes on each re-render since you are returning a newly created object each time and hence it triggers an infinite loop when you call setError within your useEffect.

Instead of adding fetchOrders as a dependency, add response and error separately

const { response, error } = useFetch(apiUrl);
useEffect(() => {
  if (error) setError(error);
  if (response) {...}
}, [response, error]);
Logo

React社区为您提供最前沿的新闻资讯和知识内容

更多推荐