I've read in several places now that accessing state in action creators is an anti-pattern. Dan Abramov has said
In general accessing state in action creators is an anti-pattern and you should avoid this when possible.
I have recently found myself in the following situation. I have 2 reducers:
currentUser:
{
currentUserId: 'abc'
}
allUsers
{
byId: {
{
abc: {
name: "John"
age: 21
}
def: {
name: "Dave"
age: 51
}
ghi: {
name: "Gunners"
age: 98
}
}
},
allIds : ['abc','def','ghi'] //this is a list; users have a certain order, that is preserved here
}
The byId /allIds
structure I have also taken from Dan Abramov / Redux
Now say I want to dispatch the following action:
export const getNextActiveUser = () => {
return {
type: "NEXT_USER"
};
};
Well, I would need to update currentUserId
to def
. But I can only get def
if I find the position of abc
in allIds
and increment the index. Only then can I update my other reducer.
I don't understand how to do this without accessing state in my action creator. Any advice?