Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: HeadslessJS and Redux - How to access store from task

We have a ReactNative app that uses redux, redux-persist and a HeadlessJS task. This task needs to have access to the store. As the task fires without booting the entire app (and so has no access by default), we thought we could simply create the store inside the task as well so that it would be rehydrated by redux-persist. It turns out, however, that the store created in this way is different from the one in the app: after running, they contain different values. We tested this in several ways and it seems indeed a problem with the stores (and not with the actions for instance) How should we access a Redux store from an HeadlessJS task?

Relevant code: store/configure.js:

configureStore = (client) => {
  const middleware = createMiddleware(client);
  const finalCreateStore = applyMiddleware(thunk, middleware, logger)(createStore);
  const store = finalCreateStore(rootReducer, undefined, autoRehydrate());

  return store;
};

In use (both in the app and in the service):

const client = new ApiClient();
const store = configureStore(client);
client.setStore(store);
persistStore(store, {
  storage: AsyncStorage,
}

In the app we simply use the Provider from react-redux to use the store, in the service we use store.dispatch.

like image 500
Joran Avatar asked Mar 03 '17 17:03

Joran


People also ask

How do you access the store in react Redux?

STEP-1 import useStore first from react-redux and then getState() function is used to access store state. STEP-2 area is the name of my slice in Redux store and areaName is state in that slice. STEP-3 FiletoSave variable is used to export JSON file with data from store.

Where is Redux store stored?

The state in Redux is stored in memory. This means that, if you refresh the page the state gets wiped out. The state in redux is just a variable that persists in memory because it is referenced by all redux functions.

Where does Redux store data in react native?

It is the object which holds the state of the application. The store is one of the building blocks of Redux. Redux is a state managing library used in JavaScript apps. It is used to manage the data and the state of the application.


1 Answers

For people looking for solution. I have found the solution in here. The idea is to bind the store to async method.

https://github.com/react-native-kit/react-native-track-player/issues/63

Copy pasting the solution here.

// index
const store = ...
....registerHeadlessTask('TrackPlayer', () => require('event-handler.js').bind(null, store));
// event-handler.js
module.exports = async (store, data) {
    if(data.type == '...') {
        store.dispatch(...);
    }
};
like image 159
Srikanth Kyatham Avatar answered Sep 22 '22 18:09

Srikanth Kyatham