Reputation: 73
I am currently working in a project which I need to consume an API to render the content. However I need to to make another request if the user changes the language. So to implement this dynamically I've inserted at the end of the URL a state called "langPage" (because only the page will change on the API) as you can see below:
componentDidMount(){
let urlData = 'https://beta.estudiocru.com/wp-json/wp/v2/pages/'+ this.state.langPage;
console.log(urlData);
fetch(urlData)
.then(response => response.json())
.then(response => {
this.setState({
aboutContent: response,
})
});
let logoURL = 'https://beta.estudiocru.com/' + this.state.lang + 'wp-json/wp/v2/acf/options';
fetch(logoURL)
.then(res => res.json())
.then(res => {
this.setState({
options: res
})
});
}
The problem is that when the state changes the fetch doesn't update and this is because I am calling it on componentDidMount
. So I would like to know how could I make another request when the state updates and re-render the new content on the page.
I am just getting started with react. I would appreciate a lot if someone could help me out.
Upvotes: 2
Views: 4893
Reputation: 2751
You can move fetch to componentDidUpdate()
it will work every time state or prop changed.
componentDidUpdate(prevProps, prevState, snapshot) {
if(this.state.lang !== prevState.lang) {
// fetch ...
}
}
Upvotes: 3