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);
      }
    )
}
4
  • 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. Commented Aug 31, 2022 at 15:42
  • I deleted it but it still running twice. Commented Aug 31, 2022 at 16:15
  • Does this answer your question? React 18, useEffect is getting called two times on mount Commented Aug 31, 2022 at 16:18
  • I understood properly now. thanks for the reply. Commented Sep 1, 2022 at 15:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.