Search code examples
reactjsreduximmutability

Redux initialState append data into existing key


I tried lot of things but I can't achieved what want. I have an initialState in redux. It has 4 coin name as you see below. I'm trying to fill this keys with value from API. But at the end I have only 1 key with data.

import { SET_LIST, GET_LIST } from '../actions'

const initialState = {
    coins: {
        'BTC': {},
        'ETH': {},
        'LTC': {},
        'DOGE': {},
    },
    loading: false,
    error: null
}


const coinsReducers = (state = initialState, action) =>  {

    switch (action.type) {

        case SET_LIST: {

            const key = action.payload.key;
            const list = action.payload.list;

            let obj = Object.assign({}, state);

            obj.coins[key] = list;
            obj.loading = true;

            return obj;

        }
        default: return state;
    }
} 

export default coinsReducers

I iterate this initial state in app.js componentDidMount hook and make api call with key. When I make api call with BTC key, I want to push the response into BTC key.

I hope someone help me.

EDIT: Working Example


Solution

  •  case SET_LIST: {
    
            const {key, list} = action.payload;
    
            return { ...state, loading: true, coins: {...state.coins, [key]: list }};
    
        }
        case GET_LIST: 
    
    // don't sure what you try to achieve here, anyhow what you are saying is that
    // from now on all the state of the app it just state.coins
    
            return state.coins
    
        default: return state;