My reducer function in state parameter (payload) returns the only proxy:
Proxy {i: 0, A: {…}, P: false, I: false, D: {…}, …}
[[Handler]]: null
[[Target]]: null
[[IsRevoked]]: true
My slice where is state proxy:
import { createSlice } from "@reduxjs/toolkit";
export const userSlice = createSlice({
name: "user",
initialState: {
currentUser: {
loggined: false,
isAdmin: false,
jwt: false,
},
},
reducers: {
setUser: (state, payload) => {
console.log(state); // here is problem, but payload works very well
},
clearUser: (state) => {},
},
});
export const { setUser, clearUser } = userSlice.actions;
export const currentUser = (state) => state.user.currentUser;
export default userSlice.reducer;
here is redux store
import { configureStore } from "@reduxjs/toolkit";
import userReducer from "../features/user/userSlice";
export default configureStore({
reducer: {
user: userReducer,
},
});
Redux Toolkit allows you to "mutate" the state by using the Immer package to create a proxied draft version of the state. You can safely mutate the state variable in your reducer functions because it is a proxy object and not the true state. Behind the scenes, your mutations of the proxy are used to return a fresh copy of the state that reflects your changes.
When you console.log the state variable you are seeing this proxy. You need to use the Immer current function which is included in Redux Toolkit in order to log the true value.
import { createSlice, current } from "@reduxjs/toolkit";
reducers: {
setUser: (state, action) => {
console.log(action);
console.log(current(state));
state.currentUser = action.payload;
},
}
Note that the second argument of the reducer is the whole action, not just the payload. The action is an object with properties type and payload. This action object is created automatically when calling setUser with a payload.
setUser({loggined: true, isAdmin: false, jwt: "some string"})
returns the action
{
type: "user/setUser",
payload: {
loggined: true,
isAdmin: false,
jwt: "some string",
}
}
You can write your reducer function as setUser: (state, action) => and access action.payload or you can destructure it as setUser: (state, {payload}) => to get a payload variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With