himori123
himori123

Reputation: 119

Redux reducer pointing(accessing) nested states

This is an issue case for my reducer.

   case GET_COIN_PRICE:
      return {
        ...state,
        coins: {
          ...state.coins,
          [action.coin.name]: {
            bithumbPrice: action.bithumbPrice,
            upbitPrice: action.upbitPrice,
            bittrexPrice: action.bittrexPrice
          }
        },
      }

I want to merge each nested states to the each original ones.

(Like ...state, ...state.coins)

The issue here is that [action.coin.name] part.

I did like :

1.

  [action.coin.name]: {
    ...state.coins.action.coin.name,
    bithumbPrice: action.bithumbPrice,
    upbitPrice: action.upbitPrice,
    bittrexPrice: action.bittrexPrice
  }

2.

  [action.coin.name]: {
    ...state.coins[action.coin.name],
    bithumbPrice: action.bithumbPrice,
    upbitPrice: action.upbitPrice,
    bittrexPrice: action.bittrexPrice

However, it returns: TypeError: Cannot read property of 'some variable' of undefined.

How can I point nested states exactly?

If you are curious about other files, For more details: https://github.com/sj602/invescoin

Upvotes: 1

Views: 48

Answers (2)

Krasimir
Krasimir

Reputation: 13529

What about the following:

case GET_COIN_PRICE:
  return {
    ...state,
    coins: Object.assign({}, state.coins,
      {
        [action.coin.name]: {
          bithumbPrice: action.bithumbPrice,
          upbitPrice: action.upbitPrice,
          bittrexPrice: action.bittrexPrice
        }
      }
    })
  }

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281686

The issue seems to come from the fact that state.coins isn't defined when you are using it, you could conditionally handle it like

case GET_COIN_PRICE:
  return {
    ...state,
    coins: {
      ...(state.coins || []),
      [action.coin.name]: {
        ...((state.coins && state.coins[action.coin.name]) || [])
        bithumbPrice: action.bithumbPrice,
        upbitPrice: action.upbitPrice,
        bittrexPrice: action.bittrexPrice
      }
    },
  }

Upvotes: 2

Related Questions