Search code examples
reactjstypescriptredux

Trying to add objects according to their category in Redux State


I am trying to solve this Redux issue with updating the state of the web application. I have a Redux state which looks like:

transcript: [
{ name: 'MATH', parts: ...}
{ name: 'ENGLISH', parts: ...}
]

I have an array coming from an API, each element of which has a category, that can be 'MATH', 'ENGLISH' and other. I am trying to map each of the element from response and add them to the specific object in my Redux state, however it just sets the whole array to null.

Here is my code, which I am using:

        transcript: {
          ...(state.transcript || {}),
          transcript:
            payload.map((part) => {
              if (state.transcript?.transcript &&
                state.transcript.transcript.find(
                  ({ name }) => name === part.category)) {
                state.transcript.transcript.map((glance) => {
                  if (glance.name === part.category) {
                    console.log(glance, part);
                    return {
                      ...glance,
                      parts: [...(glance.parts ?? []), part],
                    };
                  } else {
                    return glance;
                  }
                },
                );
              } else {
                console.log(part);
                return [
                  ...(state.transcript?.transcript || []),
                  {
                    name: part.category,
                    parts: [part],
                  },
                ];
              }
            }),
        },

I will be really grateful if you help me to solve this problem! Thank you in advance


Solution

  •         transcript: {
              ...(state.transcript || {}),
              transcript:
              state.transcript?.transcript?.map((glance) => {
                const parts = payload.filter(({ category }) => category === glance.name );
                return {
                  name: glance.name,
                  parts: [...(glance.parts ?? []), ...parts],
                };
              }),
            },