Reputation: 31
on edit action call, i want to set data in selectedEmp obj but keep getting immer error
const initialState = {
currentUser: 'user2',
users: [
{
id: 'user1', email: '[email protected]', name: 'preyash', password: '[email protected]',
loggedIn: false, selectedEmp: {},
emps: [
{ id: 1, empName: 'preyash', salary: '50000', gender: 'male' },
{ id: 2, empName: 'chintan', salary: '40000', gender: 'male' },
],
},
{
id: 'user2', email: '[email protected]', name: 'uiux5', password: '[email protected]',
loggedIn: true, selectedEmp: {},
emps: [
{ id: 1, empName: 'twisha', salary: '50000', gender: 'female' },
],
},
],
};
edit: (state, action) => {
let obj = state.users.find(i=>i.id == state.currentUser)
let index = state.users.findIndex(i=>i.id == state.currentUser)
let empObj = obj.emps.find((i) => i.id == action.payload);
state.users.splice(index, 1, { ...obj, selectedEmp: empObj })
let newUsers = current(state.users)
return {
...state,
users: newUsers
};
},
This is the output i want, Pls HELP
{
id: 'user2', email: '[email protected]', name: 'uiux5', password: '[email protected]',
loggedIn: true, selectedEmp: { id: 1, empName: 'twisha', salary: '50000', gender: 'female' },
emps: [
{ id: 1, empName: 'twisha', salary: '50000', gender: 'female' },
],
}
Here is the project url: https://stackblitz.com/edit/vitejs-vite-int6dt?file=src/reducers/userSlice.js
Upvotes: 0
Views: 1455
Reputation: 44078
In a createSlice
reducer you can just use modifying logic, so if you want to remove an element from state.users
, you just do
let index = state.users.findIndex(i=>i.id == state.currentUser)
state.users.splice(index, 1)
no additional code.
If you then want to set state.currentUser
to undefined
, you just do
state.currentUser = undefined
You do not need to return
anything from the reducer.
I'd recommend you give writing reducers with immer
a read.
Upvotes: 1