0

I am calling an api using axios inside componentDidMount and the api is being called multiple times.

Here is my code

export default class Listings extends Component{

state = {
    listings: null
}

//when the component is mounted to dom first
componentDidMount() {
    this.getAllCryptoListings();
}

getAllCryptoListings() {
    let response = null;

    axios.get('http://localhost:8000/')
        .then( (res) => {
                response = res;
                console.log(response.data.data);
            })
        .catch( (error) => console.log(error) )
        .finally( () => { this.setState({listings: response.data.data}) } )
}

}

Normally I expected the code to run one time only as per the description of the function here componentDidMount. The documentation says

You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you’ll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance.

How to make the code inside componentDidMount run only once?

StealthTrails
  • 2,281
  • 8
  • 43
  • 67

1 Answers1

0

componentDidMount() is called twice if you setState in it, you won't be able to disable this.

You can make your call in componentWillMount, but this is UNSAFE so be careful using it! (not recommended)

If this does not work you should check where your component is called. Maybe his parents are re-rendering and so calling the render to verify twice with the initial state.

You can read more about it here

In React version 18, a change was made to strict mode so that components will mount, then unmount, then mount again. This was added to help us all start catching issues that will affect an upcoming feature. In a future version of react, the state will be able to be preserved between unmounts, and as a result, components may mount multiple times.

DreamBold
  • 2,727
  • 1
  • 9
  • 24