React fetch sending request multiple times

Damla Kara

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

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.

Collected from the Internet

Please contact javaer1[email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

HotTag

Archive