sugar2code
sugar2code

Reputation: 167

React-native useEffect hook refresh fetch

I'm trying to build a react-native weather app, fetching data from the openweather api using hooks like this:

useEffect(() => {
  async function fetchWeather() {
    try {
      let data = await fetch(URL);
      const json = await data.json();
      dispatch({type: 'success', payload: json});
    } catch (error) {
      dispatch({type: 'failure'});
    }
  }
  fetchWeather(); 
}, []);

This only loads the data once. I want to make sure the weather info stays up to date. What is the best way to refresh the data? Do I poll every X minutes (if so how)?

Upvotes: 0

Views: 2745

Answers (1)

Thanh Cao
Thanh Cao

Reputation: 161

Are you looking for a period of time, you will call api?

try it:

const [isStatus, setStatus] = useState(true)
setInterval(()=> {
   setStatus(!isStatus)
}, 3000)

useEffect(() => {
   fetchWeather();
}, [isStatus])

or you only can use this function:

useEffect(() => {
  let loop = setInterval(()=> {
   fetchWeather();
  }, 3000);
 return () => clearInterval(loop);
}, [])

My example applies when the application is opening

Upvotes: 2

Related Questions