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?