How to access state inside Redux reducer?
I would use thunk for this, here's an example:
export function updateProduct(product) {
return (dispatch, getState) => {
const { accountDetails } = getState();
dispatch({
type: UPDATE_PRODUCT,
stateOfResidenceId: accountDetails.stateOfResidenceId,
product,
});
};
}
Basically you get all the data you need on the action, then you can send that data to your reducer.
Your options are to either write more logic besides just use of combineReducers
, or include more data in the action. The Redux FAQ covers this topic:
https://redux.js.org/faq/reducers/
Also, I'm currently working on a new set of pages to the Redux docs on the topic of "Structuring Reducers", which you may find helpful. The current WIP pages are at https://github.com/markerikson/redux/blob/structuring-reducers-page/docs/recipes/StructuringReducers.md .
I'm not sure if this approach is an anti-pattern but it worked for me. Use a curried function in your actions.
export const myAction = (actionData) => (dispatch, getState) => {
dispatch({
type: 'SOME_ACTION_TYPE',
data: actionData,
state: getState()
});
}