Jaseem Abbas
Jaseem Abbas

Reputation: 5230

How to read redux store from non React components?

I am building my first react native app with redux.

My store configuration is as follows

function configureStore(onComplete: ?() => void) {
  const store = autoRehydrate()(createMyAppStore)(reducers);
  persistStore(store, {storage: AsyncStorage}, onComplete);
  if (isDebuggingInChrome) {
    window.store = store;
  }
  return store;
}

I have an authentication action as follows

export function authentiate(credentials) {
  return (dispatch) => {
    return LoginApi.authenticate(credentials)
    .then(response => {
      return response.json().then(function(json) {
          dispatch(onAuthSuccess(json));
      });
    })
    .then(response => { dispatch(getUserInfo()); })
    .catch(error => {
      throw(error);
    });
  };
}

My getUserInfo action is as follows

export function getUserInfo() {
  return (dispatch) => {
    return LoginApi.gerUserInfo()
    .then(result => { dispatch(onGetUserInfoSuccess(result.json())); })
    .catch(error => {
      throw(error);
    });
  };
}

My authentication reducer is as follows

function auth(state: State = initialState, action: Action): State {
  switch (action.type) {
    case types.AUTH_SUCCESSFUL :
    return [...state, Object.assign({}, action.auth)];
    default :
    return state;
  }
  return state;
}

The LoginApi is a simple ES6 class. The getUserInfo requires details like access token and other parameters obtained from the LoginApi.authenticate call.

How do I read the authentication information from the redux store from a non-react component?

Upvotes: 0

Views: 2526

Answers (1)

azium
azium

Reputation: 20614

The second argument to redux-thunk is getState

export function getUserInfo() {
  return (dispatch, getState) => {
    const state = getState() // or cherry pick what you need
    return LoginApi.gerUserInfo(state)
    .then(result => { dispatch(onGetUserInfoSuccess(result.json())); })
    .catch(error => {
      throw(error);
    });
  };
}

https://github.com/gaearon/redux-thunk#composition

Which is just the stores own getState function.

http://redux.js.org/docs/api/Store.html#getState

you can export / import your store and call getState directly if you want.

let store = createStore(...)
export { store }

// anywhere.js
import { store } from './your-store.js'
let state = store.getState()

Upvotes: 3

Related Questions