Home > Software engineering >  react native redux: how do I update a specific value in a slice
react native redux: how do I update a specific value in a slice

Time:12-24

Here's my redux configuration:

userSlice.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  name: "",
  email: "",
  avatar: "",
  id: "",
};


export const userSlice = createSlice({
  name: "user",
  initialState: initialState,
  reducers: {
    setUser: (state, action) => {
      return {
        ...state,
        name: action.payload.name,
        email: action.payload.email,
        avatar: action.payload.avatar,
        id: action.payload.id,
      };
    },
  },
});

export const { setUser, logout } = userSlice.actions;
export default userSlice.reducer;

store.js

import { configureStore } from "@reduxjs/toolkit";
import userSlice from "./slices/userSlice";

export const store = configureStore({
    reducer: {
       user: userSlice,
    },
});

app.js

                <Provider store={store}>
                  <Stack.Navigator >
                        <Stack.Screen options={{headerShown: false}} name="Signin" component={Signin} />
                        <Stack.Screen options={{headerShown: false}} name="Home" component={Home} />
                        <Stack.Screen name="Profile" component={Profile} />
                    </Stack.Navigator>
                </Provider>      

Here's some conext:

  1. I Log in then put values into the user slice through the response of the fetch

                             const newUser = {
                               name: oj.name,
                               email: oj.email,
                               avatar: oj.avatar,
                               id: oj.sub,
                             };
                             dispatch(setUser(newUser));
    
  2. After Logging in, I console.log these values this way:

    const user = useSelector((state) => state.user);
    console.log(user)   
    

And this is what it shows:

Object {
  "avatar": "url",
  "email": "asd",
  "id": "61bcf738e954f7ffc11d507d",
  "name": "Asd",
}

I want to update name from "name": "Asd" to "name": "bill" without changing the others and this is my try:

const newUser = {                 

 name: "bill"
};
dispatch(setUser(newUser));

It works, but then the other propeties(email, avatar, id) become undefined. So how can I update a single value without touching the others?

CodePudding user response:

You can use the spread operator to merge the existing state with your new payload.

Currently, you overwrite the name, email, avatar, and id properties:

return {
        ...state,
        name: action.payload.name,
        email: action.payload.email,
        avatar: action.payload.avatar,
        id: action.payload.id,
      };

This will merge only the included properties:

return {
        ...state,
        ...action.payload,
      };
  • Related