Search code examples
reactjsreact-nativereduxredux-sagaredux-persist

get store data and dispatch outer component react native


I need to access redux store data and dispatch function outer the react component (in utils function)

I use React Native, Redux, Redux Saga, Redux Persist. my config store file is like below:

//create the saga middleware
const sagaMiddleware = createSagaMiddleware();

const encryptor = createEncryptor({
secretKey: 'encryptor_key',
  onError(error) {
  console.log('Encryptor error', error);
  // Handle the error.
 },
});

const persistConfig = {
   key: 'root',
   storage,
   transforms: [encryptor],
   whitelist: ['user', 'etc'],
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export default () => {
   const store = createStore(persistedReducer, applyMiddleware(sagaMiddleware));
const persistor = persistStore(store);

sagaMiddleware.run(rootSaga);
 return { store, persistor };
};

after user login, I save user info and oath2 token in user reducer in redux and persist that with Redux Persist. App.js is like below code:

 import configureStore from './services/configureStore';
 const { store, persistor } = configureStore();

 render() {
  return (
    <Provider store={store}>
       <PersistGate loading={<Loading style={{ flex: 1 }} />} persistor={persistor}>
        <AppNavigator />
      </PersistGate>
    </Provider>
  );
}

now, in api.js I need to access user token. I need to check oauth2 token expire time before each axios request. before axios send request I call setHeader function. my code in api.js is like below:

import configureStore from './configureStore'; //import config store

function setHeader(){
    const { store, persistor } = configureStore();
    console.log('store is:', store.getState())
}

when I call setHeader function console.log show store is empty, instead of show redux store data. anyone can help?


Solution

  • You are creating the store in App.js, so just export the store from there:

    const { store, persistor } = configureStore();
    
    export {store}
    

    Afterwards you have access to the store anywhere by simply importing it:

    import {store} from ./???/App.js