Ad

Redux Initial State Disappears On Action

- 1 answer

I have an initial state in my reducer which is an empty object

const initialState = {
    postHistory: {},
    loading: true
};

I've noticed that when I run a function from a different component which dispatches the action that this initial state actually disappears. This is causing me problems because in one of my components I'm trying to detect the present of data in this object.

const obj = this.props.postHistory;
this.props.postHistory[Object.keys(obj)[0]] && this.props.postHistory[Object.keys(obj)[0]]

However when the action is fired, I can see in redux that the initial state for the object has completely disappeared and only the loading value is there.

TypeError: Cannot convert undefined or null to object

Has any one else encountered such an issue? Any advice to overcome welcome! Thank you.

Adding reducer code as suggested:

import { POST_HISTORY } from '../actions/types';

const initialState = {
    postHistory: {},
    loading: true,
};

export default function(state = initialState, action){

    const { type, payload } = action;

    switch(type){
        case POST_HISTORY :
            return {
                ...state,
                postHistory: payload.data,
                loading: false
            }
        default:
            return state;
    }

}
Ad

Answer

First console your payload.data....then check that the data which you are getting is in "JSON" format our string format..If the data is in "Object" form then it will store in your POSTHISTORY, and if your data is in "json" format then it will not store the data in initial state.

Ad
source: stackoverflow.com
Ad