I'm trying to fetch data from a public API with Axios, and display what I get through a React app. But I can't find a condition in my componentDidUpdate() to make it render only once, when the user modifies input. Anyone'd have an idea ?
Here's my code :
import React, { Component } from 'react';
import axios from "axios";
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
input: "",
output: []
}
}
componentDidUpdate() {
axios.get(`https://geo.api.gouv.fr/communes?nom=${this.state.input}`)
.then(response => {
this.setState((prevState) => {
if (prevState.input !== this.state.input) {
return { output: response.data };
}
});
})
.catch(function (error) {
console.log(error);
})
}
handleInput = (event, input) => {
this.setState({input: event.target.value});
}
render() {
return (
<React.Fragment>
<label>Recherche : <input type="text" onChange={this.handleInput} /></label>
<div>
{this.state.output.map((value, index) => <p key={index}>{value.nom}</p>)}
</div>
</React.Fragment>
);
}
}
export default App;
Thanks for helping.
Tip: To avoid an infinite loop, all the network requests are needed to be inside a conditional statement as: componentDidUpdate(prevProps, prevState) { if (prevState. data !==
If you need to do something during the initial render, use the componentDidMount function instead.
The componentDidUpdate event is triggered whenever there is a state or props update. ComponentDidUpdate() has access to three properties, two of which are most often used more than the third. These are prevProps, prevState and lastly, snapshot, which is used less often.
The componentDidUpdate method is called after the render method of the component is done executing. That means that it will be called after all children's render methods have finished.
Assuming you need to take an action everytime your state change, you need to check if the state has updated before triggering an action
in componentDidUpdate
otherwise API call will be made whenever your component updates.
If you only wish to call the API once, then call it in componentDidMount
componentDidUpdate(prevProps, prevState) {
if(prevState.input !== this.state.input) {
axios.get(`https://geo.api.gouv.fr/communes?nom=${this.state.input}`)
.then(response => {
this.setState({ output: response.data });
})
.catch(function (error) {
console.log(error);
})
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With