Home > Blockchain >  How to change a value of an array in Redux Store Slice
How to change a value of an array in Redux Store Slice

Time:02-06

I have a Slice to store locations in it. I declared 2 functions, set and setLocation. set takes an array of locations and setLocation should set one location.

This is sample data that is in locations variable:

const locations = [{name: '1', index: 0}, {name: '2', index: 1}];

This is my slice code:

import { createSlice } from '@reduxjs/toolkit'

export const locationsSlice = createSlice({
    name: 'locations',
    initialState: {
        locations: null,
    },
    reducers: {
        set: (state, locations) => {
            state.locations = locations.payload
        },
        setLocation: (state, location) => {
            state.locations[location.index] = location
        }
    },
})

export const { set, setLocation } = locationsSlice.actions
export default locationsSlice.reducer

The set(locations) call is working. But I can't replace a single location in the location array with setLocation(location), while location is one value out of the locations array. When I do console.log(state.location) in the setLocation() function, I get some proxy object.

CodePudding user response:

The problem why you are getting Proxy in the setLocation action is because you pass location.index when searching for specific location, but you should pass location.payload.index.

setLocation: (state, location) => {
   state.locations[location.payload.index] = location
} 
  • Related