I have the following logic a chunk of a bigger state, I want to created set my rducer to dump a load of data that are fitting to main type yet missing some of the main type... my current issue is that the type is strict to that main type in other words if I want to change current Mode and current user , but I don't want to change gender, ts snaps (in dispatch) telling me I cannot assign since gender is missing how to make the argument of the reducer more flexible without using any !
// Dispach
dispatch(
setGlobalState({
currentUser: 'user',
currentMode: 'a1' || '',
// no gender ! i just dont want to update gender !
// and i dont want to make a separete call for each !
// Since the orginal logic has like 10 itmes
})
);
// Reducer
type userType = {
user: '';uid: ''
} | {
user: 'user';uid: string
}
export interface globalState {
currentUser: userType;
currentMode: 'a1' | 'a2' | 'a3';
gender: '' | 'male' | 'female';
}
const initialState: globalState = {
currentUser: {
user: '',
uid: ''
},
currentMode: 'a3',
gender: '',
};
export const globalSlice = createSlice({
name: 'global',
initialState,
reducers: {
setGlobalState: (state, action: PayloadAction < globalState > ) => {
Object.assign(state, { ...action.payload
});
}
}
CodePudding user response:
You need to do PayloadAction<Partial<globalState>>
.
But generally, please be advised that this is not a recommended "clean" way of using Redux. You should not do caclulation of new state in your component, but do so in the reducer - with the action describing the event that occured in your UI - leaving the decision what should change and how it should change to the reducer.
Please give the Redux Style Guide a read, especially the parts "Put as Much Logic as Possible in Reducers", "Reducers Should Own the State Shape", "Model Actions as Events, Not Setters" and "Write Meaningful Action Names".