0

I have my reducer where I am using Immutable and I need to update my state based on the data received from my API. The data received is an object. So every time I receive the data, I need to push that object in an array i.e. create an array of objects. Facing an issue here. Following is my code in my reducer:

import { Map, fromJS } from 'immutable';

import actionTypes from '../actions/actionTypes';

const initialState = Map({
    weather: [],
    fetchWeatherError: ''
});

export default function appReducer(state = initialState, action) {
    switch (action.type) {
        case actionTypes.FETCH_WEATHER_SUCCESS: {
            console.log("ation", action.data);
            return state.set('weather', action.data)
                .set('fetchWeatherError', '')
        }
        case actionTypes.FETCH_WEATHER_ERROR: {
            return state.set('fetchWeatherError', action.error)
                .set('weather', null)
        }

        default:
            return state;
    }
}

The line return state.set('weather', action.data) instead of updating my state I need to push the new data every time in the weather array. Please let me know if any inputs on the same, as this is just updating my state and not giving me an array.

1
  • Do you want it to be an array or a List? Commented Aug 15, 2018 at 19:35

1 Answer 1

1

Ok so to start of I recommend you to use fromJs function so that arrays are Immutable List else you'll have mixed up types and they tend to be really annoying. That said following your current implementations (meaning using arrays instead of Lists) what you can do is the following :

switch (action.type) {
        case actionTypes.FETCH_WEATHER_SUCCESS: {

            return state.set('weather',state.get('weather').concat(action.data))
                .set('fetchWeatherError', '')
        }

That will add action.data to the end of your weather array. If using Lists instead of arrays the implmenetation for this particular case would be the same/similar since they both share the concat method.

Sign up to request clarification or add additional context in comments.

1 Comment

This solves my problem. This solution will work as i have a small app. But yes, it makes sense to use fromJS. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.