简体   繁体   中英

React Redux Toolkit Multiple State Changes in One Reducer

Hey I'm still getting stumped about how redux toolkit works with state assignments in the reducers.

At the moment I am trying to create a list of names where users can add names, delete names, and update names from the list. An example array would be the following:

[{id: "A1", name: "Bob"}, {id: "A2", name: "Joe"}, {id "A3", name: "Ray"}]

I'm trying to create a delete action in my reducer which removes an element from the array by index, and then it would update all the IDs in the array accordingly. So for example if I passed in "2" into the action it would result in the following:

[{id: "A1", name: "Bob"}, {id "A2", name: "Ray"}]

The element with "Joe" would be deleted and the id of "Ray" would be updated to "A2" from "A3".

I'm trying to figure out how to go through multiple state changes as I keep running into the "immer" error with trying to assign my states to variables. I tried other methods and using a filter and then using a map to adjust the "id" afterwards, but it still didn't work. Also if I were to separate both of these state changes into individual reducers they would work. However when combined they do not work. Below is my code for it:

export const namesListSlice = createSlice(
    initialState: [{ name: "namesList", initialState: [{id: "A1", name: "Bob"}, 
                   {id: "A2", name: "Joe"}, {id "A3", name: "Ray"}], 
    reducers: {
    
        removeName: (state, action) => {
            const filteredList = state.filter((list, index) => index !== 
                                            action.payload.index);
            return filteredList.map((item, index) => {
                item.id = "A" + (index + 1);
                return item;
            });
        }
    }
});

How should I go about with changing the states two times to achieve the desire result?

It's what the error says: you can either change the object or return a new object, but not both at the same time.

So in this case, just do one of both - and in your example, doing it without mutation is probably the choice with less changes to your code.

export const namesListSlice = createSlice(
    initialState: [{ name: "namesList", initialState: [{id: "A1", name: "Bob"}, 
                   {id: "A2", name: "Joe"}, {id "A3", name: "Ray"}], 
    reducers: {
    
        removeName: (state, action) => {
            const filteredList = state.filter((list, index) => index !== 
                                            action.payload.index);
            return filteredList.map((item, index) => {
                return { ...item, id: "A" + (index + 1) };
            });
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM