Home > OS >  how to update a nested object which have made up by EntityAdapter redux?
how to update a nested object which have made up by EntityAdapter redux?

Time:11-07

I used redux createEntityAdapter() to manage my state which I've created by createSlice() , the problem is my state is nested and I don't know how to update it

this is how it's look like my state

{ids: Array(1), entities: {…}, status: 'idle', error: null}
  entities:
   aLPii2RQz4IWitooG4lqB:
    burger:
     ingredients: Array(6)
      0: {title: 'bread-tops'}
      1: {title: 'cheese', Qty: 0}
      2: {title: 'meatsss', Qty: 0}
      3: {title: 'salad', Qty: 0}
      4: {title: 'bacon', Qty: 0}
      5: {title: 'bread-bottom'}
      length: 6
  [[Prototype]]: Array(0)
  [[Prototype]]: Object
  id: "aLPii2RQz4IWitooG4lqB"
  [[Prototype]]: Object
  [[Prototype]]: Object
  error: null
ids: ['aLPii2RQz4IWitooG4lqB']
status: "idle"
[[Prototype]]: Object

for instance I'd like to increase my cheese Qty in Ingredients

   burgerAdapter.updateOne(state, {
        id,
        changes: { burger: { ingredients: {  } } },
    });

I don't know how should I loop through ingredients Array to find cheese in "updateOne" property

CodePudding user response:

The updateOne and updateMany CRUD methods only do shallow merges. So, if you want to update a more deeply nested field, you have two options:

  • Create the entire new ingredients array first
  • Don't use the CRUD methods here - write the update logic as a normal Immer-based "mutating" state update

I'd go for the second approach, personally. You already have the ID of the item, and there's only one thing that needs to be updated. So, this ought to work:

ingredientAdded(state, action) {
  const {id, ingredientName} = action.payload;
  const item = state.entities[id];
  if (item) {
    const ingredient = item.ingredients.find(ingredient => ingredient.title === ingredientName);
    if (ingredient) {
      ingredient.Qty  = 1;
    }
  }
}
  • Related