redux-persist icon indicating copy to clipboard operation
redux-persist copied to clipboard

How to get persisted state in normal function/helper files.

Open swathi2378 opened this issue 6 years ago • 6 comments

Hii.

I have a interceptor where i will add headers and token on every http request. its not a connected component nor Action creator. I need to get the persisted data here to pass it to my requests.

Store.js

let store = createStore(persistedReducer, {}, applyMiddleware(ReduxThunk)) let persistor = persistStore(store) return { store, persistor }

interceptor.js

const { store, persistor } = configureStore(); const state = store.getState(); const { userToken } = state.token;

I am always getting the initial state not persisted state. How can i achieve it??

swathi2378 avatar Aug 26 '19 14:08 swathi2378

Me too. Any answers?

basemkhirat avatar Sep 02 '19 22:09 basemkhirat

Maybe not the answer you're looking for, but I solved this by keeping my tokens outside Redux. I am storing them directly in secure storage using https://github.com/oblador/react-native-keychain. This allows me to make a secureFetch function that can be imported anywhere, which will read the access token and handle refresh, and so on.

draperunner avatar Sep 11 '19 12:09 draperunner

@swathi2378 did you find something about that? I'm trying to do exactly the same, getting persisted state outside component..

benichal avatar Jul 01 '20 11:07 benichal

Hey guys, i found the solution :

const state = store.getState(); have to be INSIDE the component

example :

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

const MyComponent = () => {
    const state = store.getState();
   /* you can use state until now and it is hydrated */
   ....
}

benichal avatar Jul 03 '20 08:07 benichal

Me too. Any answers?

sw7x avatar Apr 06 '24 02:04 sw7x

// use getStoredState api from redux-persist

import { getStoredState } from "redux-persist";  
import storage from "redux-persist/lib/storage";

async function loader()  { 
  const persistConf = {
      key: "root",
      version: 1,
      storage,
   };
   
  const state = await getStoredState(persistConf);
  console.log(state);
}

noob-programmer9012 avatar Jul 07 '24 17:07 noob-programmer9012