0

I am loading images from an api, that I will implement into a grid. My images though are not being displayed because they are undefined. Here are some functions of my component. Images and isLoading are both defined in the constructor as an empty array and to true.

componentWillMount() {
api().then((res) => {
this.state.images.push(res);
}).done();

 this._load10Images();
 this.setState({isLoading:false}); // is loading is set to false 
}                                 // after images loaded.

_getImageUrls(){
 api().then((res) => {
this.state.images.push(res);
 console.log(this.state.images); //right here works array is growing
 console.log(this.state.images[0]);//with image uris
}).done();
}

_load10Images(){
 for(let i=0; i<10; i++){
this._getImageUrls(); //call _getImageUrls 10 times to fill array
 }


}

_loadImageGrid(){

  if(this.state.isLoading){
 return <Text>Loaading ...</Text>
}
else{
 console.log(this.state.images[0]); // coming back as undefined
 return <Text>not loading ...</Text>
   }
 }

render(){ return <View>
      {this._loadImageGrid()} 
       </View>
     }

The image array come back as undefined in the render function and the _loadImageGrid function.

3
  • Changing the state property as you do is pointless. You need to use setState to trigger a new render pass. Commented Aug 11, 2016 at 21:47
  • @flq I think I see what you are saying, can you elaborate? Commented Aug 11, 2016 at 21:52
  • haha, see answer :) Commented Aug 12, 2016 at 12:04

1 Answer 1

1

I would add the following functions:

constructor(props) {
    super(props);

    this.state = {
        images: []
    }

}
_addImage(image) {
    let images = Object.assign([], this.state.images);
    images.push(image);
    this.setState({images});
}

Then you can use it like this

api().then((res) => {
    this._addImage(res);
});

Hope it helps!

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.