rt2zz / redux-persist

persist and rehydrate a redux store
MIT License
12.91k stars 863 forks source link

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

Open swathi2378 opened 4 years ago

swathi2378 commented 4 years ago

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??

basemkhirat commented 4 years ago

Me too. Any answers?

draperunner commented 4 years ago

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.

benichal commented 4 years ago

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

benichal commented 4 years ago

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 */
   ....
}
sw7x commented 3 months ago

Me too. Any answers?

noob-programmer9012 commented 2 weeks ago

// 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);
}