I'm working on a React project which is using Redux-Toolkit in JavaScript. I'm trying to shift project to TypeScript for debugging ease and Type Safety benefits. My Slices code is as
export const entitiesSlice = createSlice({
name: "entities",
initialState: initialentitiesState,
reducers: {
// getentityById
entityFetched: (state, action) => {
state.actionsLoading = false;
state.entityForEdit = action.payload.entityForEdit;
state.error = null;
},
// findentities
entitiesFetched: (state, action) => {
const { totalCount, entities } = action.payload;
state.listLoading = false;
state.error = null;
state.entities = entities;
state.totalCount = totalCount;
},
// createentity
entityCreated: (state, action) => {
state.actionsLoading = false;
state.error = null;
state.entities.push(action.payload.entity);
},
// updateentity
entityUpdated: (state, action) => {
state.error = null;
state.actionsLoading = false;
state.entities = state.entities.map(entity => {
if (entity.id === action.payload.entity.id) {
return action.payload.entity;
}
return entity;
});
},
// deleteentities
entitiesDeleted: (state, action) => {
state.error = null;
state.actionsLoading = false;
state.entities = state.entities.filter(
el => !action.payload.ids.includes(el.id)
);
},
}
}
});
But I think the assignment like this state.somevar=updatedval is doing state mutation which is not good. I want to declare my state Interface with readonly to avoid state mutation. I have gone through the Redux-Toolkit-Usage-With-Typescript, which I think should avoid state mutation but all code snippets seem to be doing state mutation. I want something like this
entityFetched: (state, action) => {
return {
...state,
actionsLoading:false,
entityForEdit:action.payload.entityForEdit,
error:null
}
}
Please guide me if I'm missing something or misinterpretting the meaning of state mutation. Any broader advice for using TypeScript with React would be most welcomed! Thanks a Lot!