jpatel701
jpatel701

Reputation: 73

Add item to an element of an array in Redux

I'm attempting to get my redux reducer to perform something like this:

To achieve .

however, I am outputting the following:

current issue

The following is the code I am using to attempt this. I've attempted to include action.userHoldings in the coinData array, however, that also ends up on a different line instead of within the same object. My objective is to get userHoldings within the 0th element of coinData similar to how userHoldings is in the portfolio array in the first image.

import * as actions from '../actions/fetch-portfolio';

const initialState = {
  coinData: [],
  userHoldings: ''
};

export default function portfolioReducer(state = initialState, action) {
  if (action.type === actions.ADD_COIN_TO_PORTFOLIO) {
    return Object.assign({}, state, {
      coinData: [...state.coinData, action.cryptoData],
      userHoldings: action.userHoldings
    });
  }
  return state;
}

Upvotes: 0

Views: 58

Answers (1)

Karan Jariwala
Karan Jariwala

Reputation: 727

I guess you want to do something like this.

    return Object.assign({}, state, {
      coinData: [ {...state.coinData[0],cryptoData: action.cryptoDatauserHoldings: action.userHoldings}, ...state.coinData.slice(1) ],

    });
  }

slice(1) is to get all elements except 0th. For the first element, you can construct object the way you like. This should do the trick. Slice returns a new array unlike splice/push or others so safe to use in reducers. :)

Upvotes: 2

Related Questions