access redux persist outside components

Viewed 494

I'm trying to access a redux store with redux persist in a service for my react native app.

I need a specific token to set a websocket connection.

My code so far:

./redux/Store.js:

const persistedReducer = combineReducers({
  tokens: persistReducer(secureConfig, TokensReducer),
});

const store = createStore(persistedReducer);

const configureStore = () => {
  const persistor = persistStore(store);

  return { persistor, store };
};

export default configureStore;

./redux/reducers/TokenReducer

const initialState = {
  accessToken: null,
  refreshToken: null
}

const TokensReducer = (state = initialState, action) {
// reducer
};

export default TokensReducer;

./service/websocket.js

import configureStore from '../redux/Store';

const { store } = configureStore();

console.log(store.getState().tokens);

The problem is, I'm not getting the persisted content, but I'm getting the initial state (accessToken = null, refreshToken = null).

When I access the store from inside my app (inside components inside and ), I get the correct values.

Edit:

when I wrap the console.log in a setTimeout() of let's say 1 second, it works! So it asynchronous, but how can I create my code to wait for it and not using setTimeout?

0 Answers
Related