Ruben Pauwels
Ruben Pauwels

Reputation: 380

Persist API data in AsyncStorage

I want to persist the fetched API data (Array) when reopening a React Native app without internet connection.

Fetching and storing the data in state and AsyncStorage works just fine using Axios.

When opening the app without internet connection, there is an endless load time, I cannot figure out how to trigger the catch promise and use my stored data as the new data for the state.

This is my code:

componentWillMount(){
        axios.get('http://example.com/api_get_request')
          .then((response) => {
              console.log('connection ok!');
              AsyncStorage.setItem('landen', JSON.stringify(response.data));
              this.setState({
                landen: response.data,
                loading: false,
              });
              //DATA SET TO STATE + ASYNCSTORAGE
          })
          .catch(error => {
            console.log(error.response);
            AsyncStorage.getItem('landen').then((value) => {
              this.setState({
                landen: JSON.parse(value),
                loading: false,
              });
              //NO CONNECTION -> ASYNC DATA
            });
          }); 
}

Upvotes: 1

Views: 1028

Answers (2)

jose920405
jose920405

Reputation: 8057

For manage some little info is a good idea use AsyncStorage. But if you need manage all your app states, it's a good practice passing your code to Redux and use libraries like:

https://github.com/rt2zz/redux-persist
https://github.com/redux-offline/redux-offline

Upvotes: 0

Vipin Kumar
Vipin Kumar

Reputation: 6546

You can use NetInfo to check internet connection and as per connection execute your code like below.

componentWillMount() {
  NetInfo.isConnected.fetch().then(isConnected => {
    if (isConnected) {
      axios.get('http://example.com/api_get_request')
        .then((response) => {
          AsyncStorage.setItem('landen', JSON.stringify(response.data));
          this.setState({
            landen: response.data,
            loading: false,
          });
        })
    } else {
      AsyncStorage.getItem('landen').then((value) => {
        this.setState({
          landen: JSON.parse(value),
          loading: false,
        });
      });
    }
  });
}

Please note, above code is not tested and you may have to fix few things here and there but you will get the concept. Also, you may have to add catch block to catch unexpected errors.

Upvotes: 2

Related Questions