Shubham
Shubham

Reputation: 45

Why axios sending get request three times to server

Instead of sending one request to get data from server why it is sending three times to get one data from server.

import React from 'react';               
import axios from "axios";
export const Components = (props) => {

  const [data, setData] = React.useState([])
  React.useEffect(() => {
    axios.get('http://localhost:8000/api/posts')
      .then(res => setData(res.data))
  },[])
  return data.map((p, index) => {
    return <p key={index}>{p.title}</p>
  })
}

export default Components;

Here you can see what output I am getting when calling an API.

enter image description here

Upvotes: 0

Views: 166

Answers (1)

acdcjunior
acdcjunior

Reputation: 135752

Because you are not providing a dependencies array (second argument) to useEffect. When you don't provide such argument, the effect is executed on every render.

Assuming you want the effect to run only once, fix it by adding an empty array:

  React.useEffect(() => {
    axios.get('http://localhost:8000/api/posts')
      .then(res => setData(res.data))
  }, []); // <------- changed here

From the docs (emphasis mine):

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

Caveat: this will still run twice during development if you are using React Strict mode.

There are new docs on the best practices for fetching data in React if you want to learn more about the subject.

Upvotes: 2

Related Questions