I'm curious about something. I was always under the impression that one could have two actions with the same name in two different reducers and that Redux would sort out the correct one to call.
So for example, say you had this setup:
And then in your React component file, when you load the correct actions file, it would just know which reducer to call. But testing reveals this not to be the case.
Am I imagining things? Is there a way to isolate and remove such conflicts? Or does one have to carefully never give two disparate reducers the same action name?
Whenever an action is dispatched, all Redux slice reducers are called and given a chance to update their state in response to that action.
Reducers normally inspect the action.type string to decide if they should handle the action, and that is normally done based on an exact string match of the action type:
// switch statements
switch(action.type) {
case 'todos/todoAdded': {}
}
// lookup tables
const caseReducer = caseReducers[action.type];
if (caseReducer) {}
So yes, if multiple reducers are looking for the exact same action type string, they will all end up updating their state in response. This is intentional - we encourage multiple reducers handling the same action.
That also means that if you want to distinguish between multiple actions, you must give each of them a unique type string.
That's why the Redux Toolkit createSlice function accepts a name string - to help make each action type more unique, so that 'sliceA/event' is different than 'sliceB/event'.
(Note that you really should be using Redux Toolkit to write all your Redux logic anyway.)
When you dispatch an action say getData it is normally associated with a type say, GET_DATA. If you name your two actions differently but with the same type, then the reducer would be triggered for all those cases where the type name matches. Thus it is better to carefully name your actions.
I usually prefer using the Ducks pattern for setting up my redux. Thus I prefix all the action type names with the duck name it belongs to. This helps me isolate the actions.
You can look into the following for more