vikeri / react-native-background-job

Schedule background jobs in React Native that run your JavaScript when your app is in the background/killed.
MIT License
747 stars 109 forks source link

redux-persist implementation? #120

Open IgorMitev opened 5 years ago

IgorMitev commented 5 years ago

Hello,

Can anybody please share their experience with implementing the package in correlation with redux-persist?

The background job is running just fine, but the store changes done while the app is killed are later not persisted to the store. Using AsyncStorage to track the changes is ok but not ideal.

Thank you

daper commented 5 years ago

Hi,

This is what I'm planning to try.

constructor () {
  let { store, persistor } = configureStore()
  this.store = store
  this.persistor = persistor
  this.state = store.getState()
}

fetchState () {
  return new Promise((resolve, reject) => {
    let unsubscribe = this.store.subscribe(() => {
      const { app } = this.store.getState()
      unsubscribe()

      this.state = app
      resolve(app)
    })
  })
}

// Some modifications in the middle

await this.persistor.persist()

Still unclear how to notify the main thread that should rehydrate its state...

IgorMitev commented 5 years ago

Hi,

Changes made to the store with the background job are persisted but the component is not reacting to them. They are reflected on the next app refresh/load.

const backgroundRedux = {
    jobKey: 'backgroundRedux',
    job: () => {
        console.log('Running background job...');
        if (AppState.currentState != 'active' && AppState.currentState != 'background') {
            store.dispatch(setFirstName('Background'));
            store.dispatch(setLastName('Job'));
            asyncStoreKey('bgupdate', true);
        }
    }
};
BackgroundJob.register(backgroundRedux);

async componentWillMount() {
    let reduxStore = store.getState().name;
    await asyncGetKey('bgupdate').then(bool => {
        if (bool) {
            this.props.refreshStore(reduxStore);
        }
    });
    asyncStoreKey('bgupdate', false);
}

Dispatching a refresh action does the trick but I'm sure there is a better way to deal with the issue.