Reputation: 10042
I am trying to append / update some data in a state array inside of my slice reducers, but when I try to console.log
the .projects
array of the state that I am interested in I just get a javascript Proxy. What is going on here (what am I doing wrong)?
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
projects: [],
};
const projectsSlice = createSlice({
name: 'projectsSlice',
initialState: { ...initialState },
reducers: {
addProject(state, action) {
const { project } = action.payload;
const newProjects = [project, ...state.projects];
console.group('add project');
console.log('project: ', project);
console.log('state projects: ', state.projects);
console.log('newProjects: ', newProjects);
console.groupEnd();
state.projects = newProjects;
},
setProjects(state, action) {
const { projects } = action.payload;
state.projects = projects;
},
removeProject(state, action) {
const { projectId } = action.payload;
const newProjects = [...state.projects].filter((project) => project.id !== projectId);
state.projects = newProjects;
},
updateProject(state, action) {
const { project } = action.payload;
const projectIndex = state.projects.findIndex((stateProject) => stateProject.id === project.id);
const newProjects = [...state.projects].splice(projectIndex, 1, project);
console.group('updateProject');
console.log('project: ', project);
console.log('projectIndex: ', projectIndex);
console.log('state projects: ', state.projects);
console.log('newProjects: ', newProjects);
console.groupEnd();
state.projects = newProjects;
},
},
});
export const { addProject, removeProject, updateProject, setProjects } = projectsSlice.actions;
export default projectsSlice.reducer;
Upvotes: 9
Views: 5250
Reputation: 494
You need to use current
import { current } from '@reduxjs/toolkit'
and with that, you can reach the current state and work with them and after that, you can send a return in reducer to return new data.
Will looks like this:
const referralSlicer = createSlice({
name: 'referral',
initialState: {
referrals: [],
currentCard: 0,
} as IReferralSlicer,
reducers: {
addReferrals(state, { payload }) {
return {
referrals: [...state.referrals, payload],
}
},
deleteReferral(state, { payload }) {
const currentState = current(state)
return {
...currentState,
referrals: currentState.referrals.splice(payload, 1),
}
},
setCurrentCard(state, { payload }) {
return {
referrals: state.referrals,
currentCard: payload,
}
},
},
})
Upvotes: 0
Reputation: 44086
The Proxy there is the reason you can just mutate state in that reducer and just get an immutable copy in your state - but browsers are really bad at logging proxies.
per the docs, you can use the current
export of RTK&immer:
const slice = createSlice({
name: 'todos',
initialState: [{ id: 1, title: 'Example todo' }],
reducers: {
addTodo: (state, action) => {
console.log('before', current(state))
state.push(action.payload)
console.log('after', current(state))
},
},
})
Upvotes: 8