EagleCode
EagleCode

Reputation: 135

add Object to array inside array with redux

Hello my problem is i wont create, update or delete {note} in array [notes] finded by operationId in parent array id. but i dont now ho to do it. i have ADDNOTE but it not working. i write i put here only ADDNOTE, becouse with these i cant event start DELETE and UPDATE

my default

const initialState = {
    loading : false,
    isLoaded: false,
    person : {
        id:'',
        firstName: '',
        operations:[],
    },
    error : ''
};


my code : 

 case ADDNOTE: return {
            ...state,
            person:
                {
                    ...state.person,
                    operations:[

                    ]
                        state.person.operations.find(item => item.id === action.payload.operationId).notes.push(action.payload)

                }

        }; 

action.payoload

{
              "id": "22",
              "operationId" : "123A",
              "note": "bla bla"
            }

what i wont :

 {
    "loading" : false,
    "person" : {
      "id": ""  ,
      "firstName": "",
      "operations":[
        {
          "id" : "123A",
          "notes": [
            {
              "id": "11",
              "operationId" : "123A",
              "note": "bla"
            },
            {
              "id": "22",
               "operationId" : "123A",
              "note": "bla bla"
            }
          ]
        },
        {
          "id" : "456B",
          "notes": [
            {
              "id": "99",
               "operationId" : "456B",
              "note": "bla xxx"
            }
          ]
        }
      ]
    },
    "error" : ""
  }

Upvotes: 1

Views: 50

Answers (1)

HMR
HMR

Reputation: 39260

I think the following would work:

case ADDNOTE: return {
  ...state,
  person: {
    ...state.person,
    operations: state.person.operations.map((operation) =>
      operation.id !== action.payload.operationId
        ? operation //not this operation, just return original
        : { // add note
            ...operation,
            notes: [...operation.notes, action.payload],
          }
    ),
  },
};

More information on how to update can be found here

Upvotes: 1

Related Questions