Search code examples
javascriptreduxreact-reduxredux-toolkit

Add a Object into state with array of Object by Redux


when my backend send a payload with value:

Object {
  "__v": 0,
  "_id": "621ef5eec33b5c6d9d184563",
  "category": "621ef5e8c33b5c6d9d18455e",
  "createdAt": "2022-03-02T04:43:26.834Z",
  "description": "",
  "name": "Hair and Nails",
  "price": 50,
  "updatedAt": "2022-03-02T04:43:26.834Z",
},

How to add this Object to my serviceReducer const initialState = { isLoading: false, error: false, serviceCategories: [], //! serviceCategories is a Array }; first of all, I map serviceCategories and selected serviceCategories that I need

        return {
            ...state,
            serviceCategories: state.serviceCategories.map((serviceCateogory) => {
                return serviceCateogory._id === action.payload.category 
                ? serviceCateogory //! here How I to add that object to services of serviceCateogory
                : serviceCateogory;
            }),
            // ),
        };

this is Structure of serviceCategories:

[
 Object {
  "__v": 0,
  "_id": "621ef5e8c33b5c6d9d18455e",
  "createdAt": "2022-03-02T04:43:20.754Z",
  "name": "Category1",
  "services": Array [
    Object {
      "__v": 0,
      "_id": "621ef5eec33b5c6d9d184563",
      "category": "621ef5e8c33b5c6d9d18455e",
      "createdAt": "2022-03-02T04:43:26.834Z",
      "description": "",
      "name": "Service1",
      "price": 50,
      "updatedAt": "2022-03-02T04:43:26.834Z",
    },
    Object {
      "__v": 0,
      "_id": "621ef7d1c33b5c6d9d1845b1",
      "category": "621ef5e8c33b5c6d9d18455e",
      "createdAt": "2022-03-02T04:51:29.262Z",
      "description": "",
      "name": "Service2",
      "price": 50,
      "updatedAt": "2022-03-02T04:51:29.262Z",
    },
  ],
  "updatedAt": "2022-03-02T05:08:35.520Z",
},
 Object {
  "__v": 0,
  "_id": "621ef5e8c33b5c6d9d18455e",
  "createdAt": "2022-03-02T04:43:20.754Z",
  "name": "Category2",
....
]

Solution

  • You need to first findIndex of the specific category from the redux state and then append the service in it. Like:

    let categories=[...state.serviceCategories];     
    let catIndex=categories.findIndex((item)=>item._id===action.payload.category);
    if(catIndex!=-1) categories[catIndex].services.push(object); // append object (service) as you wish.
    state.serviceCategories=categories;