Hello created reducer and wondering is this right pattern.
I am trying to:
Wondering if i am on right path, i don't want to mutate, so here is my code.
export const reducerCharities = (
state: CharityReducerState,
action: CharitiesAction
| CharityEditAction
) => {
switch (action.type) {
case ACTION_TYPE_EDIT:
return {
...state,
charity: {
...state.charity,
...(action.charity || {}),
},
charities: [
...state.charities.map(item => item.id === action.charity?.id ? { ...item, ...action.charity } : item)
]
}
case ACTION_TYPE:
return {
...state,
charities: [
...state.charities || [],
...action.charities
]
}
default:
return state
}
}
So my question is will this part mutate state or is there better way to write this?
charities: [
...state.charities.map(item => item.id === action.charity?.id ? { ...item, ...action.charity } : item)
]
Is this right approach how to add new item into array
{
...state,
charities: [
...state.charities || [],
...action.charities
]
}
The easiest (and since 2019 officially recommended) way of doing this would be using the official Redux Toolkit package and the createSlice
method.
Within that, you can just mutate and don't have to care about manual immutable updates - the package takes over for you.
The code could look like
const charitiesSlice = ({
name: 'charities',
initialStae: myInitialState,
reducers: {
edit(state, action: PayloadAction<Charity>){
const charity = state.charities.find(item => item.id === action.payload.id)
if (charity) {
Object.assign(charity, action.payload)
}
state.charity = action.payload
}
}
}
export const { edit } = charitiesSlice.actions
export const reducerCharities = charitiesSlice.reducer