YPCrumble
YPCrumble

Reputation: 28682

How do I perform actions while waiting for server response in react native's fetch API?

The React Native docs show the following code for React-Native's fetch API:

function getMoviesFromApiAsync() {
  return fetch('https://facebook.github.io/react-native/movies.json')
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.movies;
    })
    .catch((error) => {
      console.error(error);
    });
 }

What I'm looking for is the place to put things like a loading script while fetch is calling the server, something like the following non-working code:

function getMoviesFromApiAsync() {
  return fetch('https://facebook.github.io/react-native/movies.json')
    .whileWating(() => {
      // This is the type of thing I want to put into the fetch
      console.log('Waiting for the server response.') 
    })
    .then((response) => response.json())
    .then((responseJson) => {
      return responseJson.movies;
    })
    .catch((error) => {
      console.error(error);
    });
 }

Upvotes: 1

Views: 1131

Answers (1)

sebastianf182
sebastianf182

Reputation: 9978

The way this is usually solved is by updating the state. Like so:

Fetch:

this.setState({isLoading: true});
fetch(url)
.then((response.json()))
.then((responseJson) => this.setState({isLoading: false}));

Then in your render method something like this:

if (this.state.isLoading){
   return this.myLoadingView();
} else {
   return this.myViewWithCompletedData() 
}

Once the fetch is done, the state will update and RN will be smart enough to re render your view.

Upvotes: 2

Related Questions