Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux-Persist with React-Native-Background-Fetch

Tags:

I am creating a React-Native app that fetches data from an API as a background service.

I have looked around the web if I can manually rehydrate the store with the data fetched during the background task, but I could not find anything.

Is it possible to rehydrate the redux-persist store manually while the app is killed, from a background 'service' task?

like image 517
P.Zdravkov Avatar asked May 13 '19 20:05

P.Zdravkov


1 Answers

For the people still wondering, if it is possible to use react-native-background-fetch for scheduling ANY task, it is completely fine as long as it does not touch the UI eg. (AsyncStorage, Redux-Persist, Realm, DB...) is not directly related to invoking change in the UI, so it is completely fine to use.

In my particular case, I am using the slowest option - AsyncStorage - to persist a props sort of object which I use on global App level and pass derived data onto my components:

// Example of HeadlessTask implementation

import BackgroundFetch from 'react-native-background-fetch'
import AsyncStorage from '@react-native-community/async-storage';

const HeadlessTask = async () => {

    // Prepare data - fetching from API, other transformations...
    let propsObject = {};

    AsyncStorage.setItem(ITEM_KEY, JSON.strigify(propsObject))
        .then(() => {
            console.log('[AsyncStorage] Object Saved!');
            // For iOS specifically we need to tell when the service job
            // is done.
            BackgroundFetch.finish();
        })
        .catch((e) => {
            console.log('[AsyncStorage] Error saving object: ', e);
            BackgroundFetch.finish();
        });
}

P.S. See https://github.com/transistorsoft/react-native-background-fetch to see how to install and implement Background Fetch.

like image 143
P.Zdravkov Avatar answered Nov 15 '22 06:11

P.Zdravkov