skip to Main Content

I am trying to load the profile photo on my page before removing the loading screen, but can’t figure out how. Right now I have an "if" statement in my render function that either returns the loading screen or the rest of the page.

I display the loading screen when I am fetching the URL for the profile photo and the name of user etc from firebase. But I can’t figure out how to also display the same loading screen while the image is downloaded into my app from the URL because I download it in the JSX code.

Here is the code in my render statement:

render(){
    if (this.state.loading == true) {
        return (
            //returns jsx of a full page loading screen
        )
    }
    return (
        <View style={{ justifyContent: 'center', alignItems: 'center', marginTop: 50, marginBottom: 50 }}>
            <Image style={{ width: 150, height: 150, borderRadius: 500 }} source={{ uri: this.state.userimage }} />
        </View>
    )
}

This code is simplified but this is basically what I am doing.

Right now the loading screen shows up when I am loading the URL from firebase etc, but then I set this.state.loading to false and the loading screen goes away, but the Image still takes a few seconds to load because it wasn’t already loaded.

Could somebody tell me how to pre-load the image or some other easy way to load the image while my loading screen is still on then display it without delay?

Thank you!

2

Answers


  1. One method to do this is by fetching the image in the background, before the DOM is calling for it.

    Below is some simple code that demonstrates this functionality.

    import React from 'react';
    
    const IMAGE_URL = "https://via.placeholder.com/150";
    
    const preloadImage = (url) => {
      return fetch(url);
    }
    
    export const App = (props) => {
      const [loading, setLoading] = React.useState(true);
    
      React.useEffect(() => {
        // comment out this line and the image is not loaded until it is needed in the dom
        preloadImage(IMAGE_URL);
    
        setTimeout(() => setLoading(false), 3000);
        }, []
      );
    
      return (loading ? <span>Loading</span> : <img src={IMAGE_URL} />);
    }
    
    Login or Signup to reply.
  2. I use react-native-fast-image for my images and their preload function.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search