简体   繁体   中英

How to remove a nested array element in Redux Reducer?

been banging my head against this for hours.

I am trying to remove a nested elment of an array in an object. It must be done immutably within a reducer, which is making it tricky.

Here is the object:

questions {
    0:
    answers: [{…}]
    createdAt: "2021-04-28T01:37:21.017Z"
    creator: "607f6ab0ee09c"
    likes: []
    name: "Firstname Lastname"
}

I want to remove just 1 element of the answers array. The problem is I don't know the exact element (of questions) until I search by 'creator' code, and then I can delete the answers element by key #.

I tried using map and filter, but with 3 layers deep that logic just never worked out. I'm also open to using Immutable-js.

thanks so much, quite a baffling issue for what seems like a simple thing to do.

EDIT: I realized I can determine the key of the top level questions object in the action creator and send it over to the reducer. So all I need to know how to do is remove an element of an array in an object, nested in another object.

thanks for any help!

First of clone your questions object by using ... ES6 operator

const clonedQuestion = {...questions}

Now for removing element from answers array

const indexOfElementToRemove = clonedQuestion.answers.findIndex(element => element.creator === clonedQuestion.creator);
if(indexOfElementToRemove >= 0) {
  clonedQuestion.answers.splice(indexOfElementToRemove, 1)
}

You might also take a look at the official redux toolkit, which would allow you to just use mutating logic like this in their createReducer - or createSlice - created reducers:

delete state.questions.answers[5]

See this tutorial page that gives a short overview over what we consider as "modern redux":https://redux.js.org/tutorials/fundamentals/part-8-modern-redux

If that is not something you want to do right now (keep in mind though, that modern redux and legacy redux can be mixed in an application), look into immer instead of immutable since immutable is essentially dead at this point and immer has a much better developer experience.

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