2

I'm trying fetching data in react. I call the fetch function only once but it's sending request multiple times but I don't know why. I looked other questions and tried their answers but none of them worked.

When I delete useEffect and leave the function alone, it sends a request once, but I think this is not the right way.

useEffect(() => {
  fetchFunction();
}, [])

const fetchFunction =() => {
  console.log("ldşsaşdlisaldi")
  axios.get(
    "someAPI",
    {
      headers: {
        "Authorization" : localStorage.getItem("token")
      },
      credentials: 'include',
    }
  )
    .then(res => res.json())
    .then(
      (result) => {
        console.log(result)
        setIsLoaded(true);
        setTableData(result);
      },
      (error) => {
        setIsLoaded(true);
        setError(error);
      }
    )
}
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
Damla Kara
  • 35
  • 7
  • 1
    Have you checked by the way if your index.js is running strict mode. It's for development purposes only, if it is try removing strict mode and retry is see if the request are still running twice. – Jericho Aug 31 '22 at 15:42
  • I deleted it but it still running twice. – Damla Kara Aug 31 '22 at 16:15
  • Does this answer your question? [React 18, useEffect is getting called two times on mount](https://stackoverflow.com/questions/72238175/react-18-useeffect-is-getting-called-two-times-on-mount) – Youssouf Oumar Aug 31 '22 at 16:18
  • I understood properly now. thanks for the reply. – Damla Kara Sep 01 '22 at 15:20

1 Answers1

3

Don't attempt to do any sort of "initial mount" check or "state" as this is considered anti-pattern. Don't try to "outsmart" React. The double-mounting is a way for the React.StrictMode component to help you see unexpected side-effects and other issues. You should implement a cleanup function to cancel any in-flight requests when the component unmounts. Use an abortController with the axios GET request.

Example:

useEffect(() => {
  const controller = new AbortController(); // <-- create controller

  fetchFunction({ controller }); // <-- pass controller

  return () => controller.abort(); // <-- return cleanup function
}, []);

const fetchFunction = ({ controller }) => {
  axios.get("someAPI", {
    headers: {
      "Authorization" : localStorage.getItem("token")
    },
    credentials: 'include',
    signal: controller.signal // <-- pass signal to request
  })
    .then(res => res.json())
    .then((result) => {
      console.log(result);
      setTableData(result);
    })
    .catch((error) => {;
      setError(error);
    })
    .finally(() => {
      setIsLoaded(true);
    });
}

For more details and explanation see Fetching Data.

Drew Reese
  • 165,259
  • 14
  • 153
  • 181