Sinan Samet Sinan Samet - 11 months ago 95
React JSX Question

Is it possible to cache an api request with react native/redux?

I haven't been able to figure out if I can cache the api calls locally so that when I close the app and restart it it's still there.

On this page of Redux I saw that it is possible to cache with middleware like this:

loadData(userId) {
// Injected into props by React Redux `connect()` call:
let { dispatch, posts } = this.props

if (posts[userId]) {
// There is cached data! Don't do anything.

// Reducer can react to this action by setting
// `isFetching` and thus letting us show a spinner.

// Reducer can react to these actions by filling the `users`.
response => dispatch(loadPostsSuccess(userId, response)),
error => dispatch(loadPostsFailure(userId, error))

Should I use that? And does the cache remain after closing the app?

Answer Source

We can use Redux Persist library to persist the redux store. By default this library will persist the entire redux store. But in your case you need to persist only some API calls. What you need to do is, add all the stores that has to be persisted to the whitelist like below.

    store, {
        storage: AsyncStorage,
        whitelist: ['user','some_other_reducer'],
    }, onComplete);

You may refer f8App by facebook for the implementation details on how to set up redux persist.