Home » Javascript » javascript – fetch return old data when offline

javascript – fetch return old data when offline

Posted by: admin February 24, 2020 Leave a comment

Questions:

In my React Native app random image rerender every N second. I get link to random image from API. When I turning off the Internet, fetch returns a link to the image from the previous successful request every N second.
Also status.code=200 and catch is not working. (I don’t know why). I would like to show error message, when offline

const [value, setValue] = useState(3);
const [imgUrl, setImgUrl] = useState();
const [isError, setIsError] = useState(false);

const getImage = () => {
        fetch('https://dog.ceo/api/breeds/image/random',{'cache':'no-store'})
            .then( response => {
                if (response.ok) {
                    return response.json();
                } else {
                    setIsError(true);
                }
            })
            .then( responseJson => {
                setImgUrl(responseJson.message);
            })
            .catch((error) => {
                console.warn(error);
                setIsError(true);
            });
    };

useEffect(() => {
  getImage();
}, []);

useEffect(() => {
  const timer = setInterval(getImage, value * 1000);
  return () => clearInterval(timer);
}, [value]);

return(
 <View style={styles.imageView}>
    {isError === false ? <Image style={styles.img} source={{ uri: `${imgUrl}` }} /> : <View><Text>Please, check your network connection!</Text></View>}
 </View>
 <Slider value={value} onValueChange={(sliderValue) => setValue(sliderValue)}/>
);
How to&Answers: