I am working on a react app where I am using redux for state management,I am new to this and I have to do multiple state change operations inside a reducer function.
Here’s my reducer function:
case Actions.ON_SUBMIT_CLIENT: { return { ...state, clientList: [...state.clientList, action.client] } }
What I want to do is,add a item to clientList
which I am doing here and then re-assign 2 variables clientName
and clientStatus
too like:
case Actions.ON_SUBMIT_CLIENT: { return { ...state, clientList: [...state.clientList, action.client], clientName: "", clientStatus: "", clientAccessGrants: [] } }
How can I achieve this inside the reducer function? Any help will be highly appreciated.
Here’s my github link: here
you can see the reducer in clientReducer,the ON_SUBMIT action call in Form/PopupActions.
Advertisement
Answer
Issue
You’ve declared the values outside the return.
case Actions.ON_SUBMIT_CLIENT:{ clientName:""; // <-- not returned clientStatus:""; // <-- not returned clientAccessGrants:[] // <-- not returned return { ...state, clientList: [...state.clientList, action.client], } }
Solution
If you want to update the state they need to be returned as part of the next state value returned from the reducer case.
case Actions.ON_SUBMIT_CLIENT: return { ...state, clientList: [...state.clientList, action.client], clientName: ""; clientStatus: ""; clientAccessGrants: []; }
Update
So it seems you are either dispatching the wrong action or handling the wrong action in the reducer.
The submitClient
action creator dispatches an action of type Actions.SUBIMT_CLIENT
('CLIENT/SUBIMT_CLIENT'
) but the reducer case you have is handling an action of type Actions.ON_SUBMIT_CLIENT
('Actions.ON_SUBMIT_CLIENT'
). There’s a typo in the spelling of “submit” in the action creator so this one was tricky tracking down.
Updating the reducer to handle the same action type that is dispatched now clears/resets the other state.
case Actions.SUBIMT_CLIENT: { return { ...state, clientList: [...state.clientList, action.client], clientName: "", clientStatus: "", clientAccessGrants: [] }; }
Here’s a codesandbox fork of your github repo. I added the redux dev tools so if you have the extension you can see the actions as they are dispatched and check the state diff.