0

I'm trying to learn React by building a "movie search app". The main problem is that, I have an array of request URLs and I want to retrieve each object and push them into a state array and then update the state, however pushing to the state array doesn't work.

promises = arr.map(el=>fetch(requesturl).then(e=>e.json()))
result = promises => Promise.all(promises).then(value=>console.log(value));

The code looks something like this. Instead of printing them into the console, I want to save all of them and then update the view.

Apologies, if the question is unclear.

4
  • Right, you don't push to the state array. You should create a copy of the array, append the new resuts, then setState in the component with the new array Commented Jul 14, 2018 at 21:46
  • did you mean this? result = promises => Promise.all(promises).then(value=>{ let arr = this.state.titles.concat(value); this.setState({titles : arr}); }); Commented Jul 14, 2018 at 21:51
  • Yeah give that a try Commented Jul 14, 2018 at 21:51
  • Already did that, but the problem is that page is not loading. It looks like it is, but never finishes. I don't know why. By the way, it is correct to call this method in componentDidUpdate? Because I did it so that the view would be updated when state changes. Commented Jul 14, 2018 at 21:55

1 Answer 1

1

You can do it simply in a then after Promise.all like so:

const arr = ['google.com', 'youtube.com']

class MoviesList extend Component{
  state = { movies: [] }

  componentDidMount(){
    const promises = arr.map(el=>fetch(requesturl).then(e=>e.json()));
    Promise.all(promises).then(movies => this.setState(movies));
  }

  render(){
    return <div>{JSON.stringify(this.state.movies)}</div>
  }
}

Worked jsfiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Tried it, returns an empty array :/
@MensurQulami i added worked example :) Please check it

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.