2

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?

R. Kohlisch
  • 2,823
  • 6
  • 29
  • 59
  • I think the philosophy here would be to have truly reusable action creators that are "pure" aka only rely on parameters, not on state. You _can_ however access the state and get stuff out of it and then pass it as parameters to your action creators, but that is _application_ specific behaviour and not something action creators should know of. You can easily wrap this in helper functions which are part of the "UI" and not the "State" part of the application. – Sergiu Paraschiv Aug 06 '19 at 13:14

0 Answers0