Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload images before navigating to component

Tags:

react-native

This is more of a conceptional question, but I am not sure the exact way to solve it.

I have a component I want to download images from, but I want to be able to indicate that the component is loaded before the user can then use router flux to switch to it.

I am guessing that is something I would have to accomplish in redux, is that the right idea? I've been trying to find an example of a react native app that does this.

Thanks so much!

like image 277
Joe Caraccio Avatar asked Mar 09 '17 22:03

Joe Caraccio


1 Answers

RN Image component a specific static method to handle this case: https://facebook.github.io/react-native/docs/image.html#prefetch

Note: Image.prefetch returns a Promise

Below is an example of how to implement this using React Native Router Flux (RNRF), without using Redux:

let urlOfImages = [https://...]

let preFetchTasks = []; 

urlOfImages.forEach((p)=>{
    preFetchTasks.push(Image.prefetch(p));
});

Promise.all(preFetchTasks).then((results)=>{
    let downloadedAll = true;
    results.forEach((result)=>{
        if(!result){
            //error occurred downloading a pic
            downloadedAll = false;
        }
    })

    if(downloadedAll){
        Actions.someScene({ downloadedPics: urlOfImages})
    }
})

Then in your someScene component use the image component like you normally do and the image will be fetched from your local disk cache rather then remotely :

 <Image style={...} source={{uri: this.props.urlOfImages[0]}} />

Also just be aware you'll have issues if you attempt to load images from http rather than secured https endpoints: https://github.com/facebook/react-native/issues/8520

If you wanted to use it with Redux put the above code in an Action and make sure your reducers respond to the action and set the new state as per your application requirements.

like image 138
Shivam Sinha Avatar answered Oct 20 '22 12:10

Shivam Sinha