Recommand · May 22, 2021 0

React Redux how to add data to object's array

My user structure is:

user = {
email: ’email’,
flashcards: []
}

And i would like to add data into user’s flashcards array (using redux)

My user-reducer

import { UserActionTypes } from './user.types';

const INITIAL_STATE = {
  currentUser: null,
};

// GETS STATES OBJ AND RECIVES AN ACTION
const userReducer = (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case UserActionTypes.SET_CURRENT_USER:
      return {
        ...state, 
        currentUser: action.payload, 
      };
    case UserActionTypes.ADD_FLASHCARD:
      return {
        ...state,
        currentUser: action.payload,
      };

    default:
      return state;
  }
};
export default userReducer;

user-actions

export const addFlashCard = user => ({
  type: UserActionTypes.ADD_FLASHCARD,
  payload: user.flashcards,
});

And when i’m doing so my payload is undefined.

Could you give me some hints?

You are currently overwriting currentUser with the value of user.flashcards from the redux action. To add new flashcards, the ADD_FLASHCARD branch of your reducer should look more like this:

case UserActionTypes.ADD_FLASHCARD:
  return {
    ...state,
    currentUser: {
      ...state.currentUser,
      flashcards: [
        ...state.currentUser.flashcards,
        ...action.payload
      ]
    }
  };