1

I have a Redux reducer with the following state:

const INITIAL_STATE = {
  permissions: [''],
  authzError: null
};

I already have some Redux actions that modify state.permissions. I am writing the following action to run permission checks:

export function isAuthz(allowed, except) {
  // I need state.permissions here
  ...
}

I know I can do this:

export function isAuthz(allowed, except, permissions) {
  // Now do permission check
  ...
}

But this means pulling state.permissions out in the component and then putting it in the isAuthz action, which seems like a waste and error prone. I could just check permissions in the reducer, but I thought an action is where I am suppose to do this.

Where should I do this permission check and how do I get a hold of state.permissions ?

Thanks,

Warren

Warren
  • 735
  • 7
  • 19
  • If it's something that can be calculated from `state.permissions`, then there is no reason for it to be in `state`. You can just extract that to a function and calculate it dynamically. For example in `connect`. – Sulthan Mar 08 '18 at 18:20
  • Also, if you are using redux-thunk, see https://stackoverflow.com/questions/35667249/accessing-redux-state-in-an-action-creator – Sulthan Mar 08 '18 at 18:23

3 Answers3

5

You can get the state in your actions too.

For example in this action you can do this:

export function isAuthz(allowed, except) {
  return (dispatch, getState) => {
    const state = getState()
    // do stuff
  }
} 
Arnold Gandarillas
  • 3,896
  • 1
  • 30
  • 36
4

if you're exporting your store from a module

export default createStore(...)

just import it

import store from '../path/to/store'

export function isAuthz() {
  const state = store.getState()
  ... // use state.permission
}

edit: as others have pointed out, if you're using redux-thunk, a getState argument is provided to you as the second param in the thunk

export function isAuthz(...) {
  return function (dispatch, getState) {
    const { permission } = getState()
  }
}
Tyler Sebastian
  • 9,067
  • 6
  • 39
  • 62
1

I find the answer right after I post the question. You can use redux-thunk to get the state.

export function isAuthz(allowed, except) {
  return (dispatch, getState) => {
     const { permissions } = getState();
     // Now do permission check
  };
}

Hope this helps someone else.

Warren

Warren
  • 735
  • 7
  • 19