Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
28
rated 0 times [  34] [ 6]  / answers: 1 / hits: 22493  / 8 Years ago, sat, july 23, 2016, 12:00:00

I'm wondering, sometimes I have a reducer that needs information from another reducer. For example I have this reducer:



import * as ActionTypes from '../actions/action_type_constants';
import KeyCode from 'keycode.js/index';
import {store} from ../index;
import {mod} from ../pure_functions;

export function selectedCompletion(state = 0, action) {
if (action.type === ActionTypes.arrowKeyPressed) {
const completionsLength = store.getState().completions.data.length;
if (action.keyCode === KeyCode.UP) {
return mod(state - 1, completionsLength);
} else if (action.keyCode === KeyCode.DOWN) {
return mod(state + 1, completionsLength);
}
}
return state;
}


I do call store.getState at the second line of the function, because otherwise I can not determine the index correctly.



I could probably refactor this and the other reducer, so that it becomes one big reducer, but for readability I would prefer this option.



I'm not sure if I would get somehow into problems if I use this pattern of calling store.getState() in a reducer.


More From » redux

 Answers
20

Yes, this is absolutely an anti-pattern. Reducer functions should be pure, and only based on their direct inputs (the current state and the action).



The Redux FAQ discusses this kind of issue, in the FAQ on sharing state between reducers. Basically, you should either write some custom reducer logic that passes down the additional information needed, or put more information into your action.



I also wrote a section for the Redux docs called Structuring Reducers, which discusses a number of important concepts related to reducer logic. I'd encourage you to read through that.


[#61270] Thursday, July 21, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jadyngraysons

Total Points: 455
Total Questions: 109
Total Answers: 98

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
jadyngraysons questions
Thu, Apr 23, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
Tue, Dec 31, 19, 00:00, 4 Years ago
;