I have a reducer, and in order to calculate the new state I need data from the action and also data from a part of the state not managed by this reducer. Specifically, in the reducer I will show below, I need access to the accountDetails.stateOfResidenceId
field.
initialState.js:
export default { accountDetails: { stateOfResidenceId: '', accountType: '', accountNumber: '', product: '' }, forms: { blueprints: [ ] } };
formsReducer.js:
import * as types from '../constants/actionTypes'; import objectAssign from 'object-assign'; import initialState from './initialState'; import formsHelper from '../utils/FormsHelper'; export default function formsReducer(state = initialState.forms, action) { switch (action.type) { case types.UPDATE_PRODUCT: { //I NEED accountDetails.stateOfResidenceId HERE console.log(state); const formBlueprints = formsHelper.getFormsByProductId(action.product.id); return objectAssign({}, state, {blueprints: formBlueprints}); } default: return state; } }
index.js (root reducer):
import { combineReducers } from 'redux'; import accountDetails from './accountDetailsReducer'; import forms from './formsReducer'; const rootReducer = combineReducers({ accountDetails, forms }); export default rootReducer;
How can I access this field?
STEP-1 import useStore first from react-redux and then getState() function is used to access store state. STEP-2 area is the name of my slice in Redux store and areaName is state in that slice.
The only way to update a state inside a store is to dispatch an action and define a reducer function to perform tasks based on the given actions. Once dispatched, the action goes inside the reducer functions which performs the tasks and return the updated state to the store. This is what Redux is all about.
Reducers are the only way to change states in Redux. It is the only place where you can write logic and calculations. Reducer function will accept the previous state of app and action being dispatched, calculate the next state and returns the new object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With