Hareesh
Hareesh

Reputation: 1587

ReactJS How to prevent multiple API calls occurring in componentDidMount function

I have the following axios request given inside componentDidMount function and when I inspect the network I found API called 6 times. What will be the reason for this much calls triggered and is there any other function or solutions to solve this?

componentDidMount(){
     axios.get(this.state.url+'tables', { headers: { 'authorization': token } })
     .then(response => { 
         const regions = response.data.data.regions,
                state = response.data.data.state,
                directory = response.data.data.directory,

         this.setState({ regions,state,directory });
     })
     .catch((error) => {
         console.log('error ' + error);
      });

}

Upvotes: 1

Views: 1779

Answers (2)

Marek Bernád
Marek Bernád

Reputation: 629

Quick fix, I recommend reading the article within the lower link, but for local testing, remove React.StrictMode (these two lines) from index.js:

ReactDOM.render(
  <React.StrictMode> //<--- REMOVE
    <App />
  </React.StrictMode>, //<--- REMOVE
  document.getElementById('root')
);

Credits to:

Upvotes: -1

Subin Sebastian
Subin Sebastian

Reputation: 10997

It should be because there will be 6 instances of this component rendered in your client. Maybe you are including this component inside say an array.map

Upvotes: 2

Related Questions