Reputation: 13
I called an API using fetch inside a componentDidMount but i need the API URL to change with the state I set in a textInput.
I can see my state is changing in console.log() but it seems it's not changing inside the componentDidMount.
constructor(props) {
super(props)
this.state = {
codigoCarro: "", //this is the state i need to change
}
}
componentDidMount() {
fetch
(`https://parallelum.com.br/fipe/api/v1/carros/marcas/${this.state.codigoCarro}/modelos`) //i need the state to change here
.then((response) => response.json())
.then((responseJson) => {
this.setState({
modeloCarro: responseJson.modelos
})
})
.catch((error) => {
console.log(error)
})
}
render() {
return (
<Text>Please insert the number informed in the input below</Text>
<TextInput
placeholder="Código da marca"
onChangeText={(codigoCarro) => {
this.setState({ codigoCarro });
}}
/>
);
}
Upvotes: 0
Views: 252
Reputation: 2220
It might be worth reading over the React documentation for componentDidMount() as this function is only called once the component is inserted into the dom tree meaning it will not be called every time your state updates.
You might be looking for the componentDidUpdate() function which is called after each render, however, I would still read the documentation as you may introduce excessive netowrk requests by changing this.
The final product may look something like this:
componentDidUpdate(prevProps, prevState) {
if(prevState.codigoCarro == this.state.codigoCarro) return;
fetch
(`https://parallelum.com.br/fipe/api/v1/carros/marcas/${this.state.codigoCarro}/modelos`) //i need the state to change here
.then((response) => response.json())
.then((responseJson) => {
this.setState({
modeloCarro: responseJson.modelos
})
})
.catch((error) => {
console.log(error)
})
}
Upvotes: 2