Mike jones Mike jones - 3 months ago 20
React JSX Question

How to properly load data react native

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.

Answer

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!

Comments