简体   繁体   中英

update dynamic object in redux using spread operator

I am trying to update an object in redux using spread operator but I am not being able to. Initial state is an empty object because category is received dynamically from api call.
pages and data are both objects which i want to update using spread operator (or whatever works best)

 state = {
      [category]: {
        pages: {
          key: value(array)
        },
        data: {
          key: value(array)
        }
      }
    }

At my reducer I try to update it like this

 return {
        ...state,
        [category]: {
          ...state[category],
          pages: { ...state[category].pages, pages },
          data: { ...state[category].data, doctors },
          total: total,
        },
      };

but i get "error: TypeError: Cannot read property 'pages' of undefined"

What am I doing wrong and how can I update them correctly?

Because state.category is undefined when you fetch this category for the first time. You can fix it like that:

return {
  ...state,
  [category]: state.category
    ? {
        ...state[category],
        pages: { ...state[category].pages, pages },
        data: { ...state[category].data, doctors },
        total: total,
      }
    : {
        pages,
        data: doctors,
        total,
      },
};

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