Axen_Rangs
Axen_Rangs

Reputation: 427

Update one parameter using Redux Tool kit

When I'm trying to update only one parameter of the following store other values automatically getting updated to their initial state. How can I prevent this?

My slice.js

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
  value: 0,
}

export const userSlice = createSlice({
  name: 'user',
  initialState:{value:{name:"name",email:"",age:"",hobby:"",grade:""}},
  reducers: {
    login:(state,action)=>{
        state.value =action.payload;
    }
  },
})

export const { login } = userSlice.actions

export default userSlice.reducer

Updating the value

if (value.topic=="cred") {

  console.log(value.username)
  dispatch(login({name:value.username}));
  console.log("Value dispatched",user.name)
}

Upvotes: 0

Views: 1754

Answers (1)

remarcoble
remarcoble

Reputation: 683

If you just overwrite value you have to pass all the other properties as well, so you have 2 options to accomplish this.

Option 1

You just pass name to the function and then change only that value.

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
   name: "name",
   email: "",
   age: "",
   hobby: "",
   grade:""
}

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    login: (state,action) => {
        state.name = action.payload
    }
  },
})

export const { login } = userSlice.actions

export default userSlice.reducer

And then you call it like this.

if (value.topic=="cred") {

  console.log(value.username)
  dispatch(login(value.username));
  console.log("Value dispatched",user.name)
}

Option 2

You're able to modify different field with the same reducer, even though I suggest creating more reducers.

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
   value: {
      name: "name",
      email: "",
      age: "",
      hobby: "",
      grade:""
   }
}

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    login: (state,action) => {
        state.value = action.payload
    }
  },
})

export const { login } = userSlice.actions

export default userSlice.reducer

And then you call it like this.

const user = useSelector((state) => state.user)

if (value.topic=="cred") {

  console.log(value.username)
  dispatch(login({...user, name: value.username})); // You can modify also multiple value at once with {...user, name: value.username, hobby: "Something"}
  console.log("Value dispatched",user.name)
}

Upvotes: 1

Related Questions