1

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?

3
  • it seems like you are trying to update reducer before getting API data or you don't or pages does not exists in your response Commented Jul 20, 2020 at 14:56
  • pages do exist in the response because if i just set pages:pages, it will get the values, but it overwrites it and i want to update it with previous results Commented Jul 20, 2020 at 15:14
  • then category does not exists in the state (state[category])that you are searching at first time ! Commented Jul 20, 2020 at 15:15

1 Answer 1

1

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,
      },
};
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much. it worked. just had to change [category]: state[category] ? { ...
I'm glad that helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.