2

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.

2
  • everytime state changes, component renders, why dont you call this in render? Commented Jun 6, 2018 at 20:07
  • Thanks Hashbytes! The URL changes correctly but the content doesn't. It is still the same content of the first fetch Commented Jun 6, 2018 at 20:15

1 Answer 1

3

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 ...
   }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.