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 [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

TOP Ranking

  1. 1

    How can I create a column whose entries depend on the contents of a column in another table?

  2. 2

    pump.io port in URL

  3. 3

    How to display items using sessions

  4. 4

    BigQuery - concatenate ignoring NULL

  5. 5

    no applicable method for 'mutate_' applied to an object of class "c('integer', 'numeric')"

  6. 6

    How i extract text from a model dialog in selenium?

  7. 7

    x no applicable method for 'tbl_vars' applied to an object of class "c('double', 'numeric')"

  8. 8

    AirflowException: Celery command failed - The recorded hostname does not match this instance's hostname

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    Most efficient regex for checking if a string contains at least 3 alphanumeric characters

  11. 11

    using excel range find return Type mismatch. (Exception from HRESULT: 0x80020005 (DISP_E_TYPEMISMATCH))

  12. 12

    redirect your computer port to url

  13. 13

    Can't create database with Symfony 4.1 : could not find driver

  14. 14

    How to fix "Exception evaluating SpringEL expression" error after submitting a variable Spring/Thymeleaf

  15. 15

    A python function to get the maximum value of a specific column, given a string that represents a table in CSV format

  16. 16

    Double spacing in rmarkdown pdf

  17. 17

    Uploading Files on production server returns either CORS error or POST 400 Bad Request using Apollo-Graphql

  18. 18

    Android Kotlin Unit test failing with io.mockk.MockKException: no answer found for

  19. 19

    Change Model input_shape but got an : ValueError: Input 0 of layer dense_44 is incompatible with the layer

  20. 20

    Formik, Yup - How to check is Decimal number

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive