Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access state inside Redux reducer?

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?

like image 829
kibowki Avatar asked Aug 31 '16 19:08

kibowki


People also ask

How do I get my state from Redux?

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.

How do I change my state in Redux Reducer?

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.

What is state in reducer in Redux?

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.


1 Answers

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.

like image 94
Crysfel Avatar answered Sep 21 '22 06:09

Crysfel