skip to Main Content

I am new to React. I have a GET API. First I will load in ueEffect.

Whenever I am calling that my browser showing that API is running infinite time.
I did something in the useEffect dependency by providing wrong function . But I don’t know how to stop that. Added screenshots below

This is my useState that holds the data:

const [loadData, setLoadData] = useState([]);

This is my async function I am setting my state in:

const fetchData = useMemo(() => async => {
  try {
    const responseData = await axios.get(baseUrl { withCredentials: true })
    const details = await responseData.data;
    setapiLoading(false); //loader false
    if (details.length === 0) {
      setLoadData(null);
    }
    else {
      setLoadData(details);
    }
  }
  catch (error) {
    toast.error( error + ':Please try again', { position: toast.POSITION.TOP_CENTER })
  }
}

useEffect(() => {
  fetchData();

}, [fetchData]);

In this image, the effect is running forever:

endless loop

How can I solve this? Thanks in advance.

2

Answers


  1. The effect runs every time fetchData changes. The reference to fetchData changes every time loadData changes. So, the effect runs every time loadData changes (continuously).

    To fix it, put everything inside the effect so it only runs once on mount:

    useEffect(() => {
      const fetchData = async () => {
        // your function
      }
      fetchData();
    },[])
    
    Login or Signup to reply.
  2. the reason why it running infinitely because you pass loadData as a dependency to useMemo() for fetchData. as a result, every time you calling setLoadData(), useMemo will return new instance of fetchData, which subsequently triggers useEffect().

    Here is how you can solve it by defining fetchData inside useEffect:

       const [loadData, setLoadData] = useState([])
       useEffect(() => {
          async function fetchData() {
            try {
              setApiLoading(true);
              const responseData = await axios get(baseURL, { withCredentials: true });
              const details = await responseData.data;
              if(details.length === 0) {
                setLoadData(null);
              } else {
                setLoadData(details);
              }
            } catch(error) {
              toast.error( error + ':Please try again', { position: 
      toast.POSITION.TOP_CENTER });
            } finally {
              setApiLoading(false);
            }
          };
    
          fetchData();
       }, [])
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search