Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does React Native Image tag have retry functionality?

I want to use Image this way:

<Image
  source={{
    uri: 'https://facebook.github.io/react/logo-og.png',
    method: 'POST',
    headers: {
      Pragma: 'no-cache',
    },
    body: '...',
  }}
  style={{width: 400, height: 400}}
/>

But I want that if the image fails it will try to re-load it again.

Do we have that option on React Native? I know about the onError function but I don't know how to make the image to reload again.

Thanks.

like image 739
maya dahan Avatar asked May 15 '26 23:05

maya dahan


1 Answers

@mindmaster's solution is not practical, try to pass a different key for the image in each retry to re-render the Image component.

It is even easier with Hooks:

const MyComponent = () => {
    const [retryCounter, setRetryCounter] = useState(0);

    const onImageLoaded = useCallback(() => {
        console.log('Image loaded!');
    }, []);

    const onImageError = useCallback(() => {
        Alert.alert('Error', "Can't load the image!", [
            {
                text: 'Cancel',
                style: 'cancel',
            },
            {
                text: 'Retry',
                onPress: setRetryCounter((prevCounter) => prevCounter + 1),
            },
        ]);
    }, []);

    return (
        <View>
            <Image
                key={`image-${retryCounter}`}
                source={{
                    uri: 'https://facebook.github.io/react/logo-og.png',
                    method: 'POST',
                    headers: {
                        Pragma: 'no-cache',
                    },
                    body: '...',
                }}
                style={{ width: 400, height: 400 }}
                onLoad={onImageLoaded}
                onError={onImageError}
            />
        </View>
    );
};
like image 133
parse Avatar answered May 18 '26 20:05

parse