0
votes

I'm receiving my redux state in the mapStateToProps function, but the state is not mapping to props and therefore not usable in my component.

I've run a console.log in the mapStateToProps function and received data back. The props are not being assigned with the state object/array (the console.log has an array coming back).

HELP!

MY COMPONENT:

componentDidMount() {
        this.props.onLoadHabits();
        console.log(this.props.habits)
        // undefined
    }

const mapStateToProps = state => {
    console.log(state.habits.habits)
    // returns an array with my two test objects included... [ Object, Object]
    return {
        habits: state.habits.habits
    }
}

const mapDispatchToProps = dispatch => {
    return {
        onLoadHabits: () => dispatch(getHabits())
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(RoutineScreen);

MY ACTION:

export const getHabits = () => {
    return dispatch => {
        fetch("https://bestlyfe-b368a.firebaseio.com/habits.json")
            .catch(err => {
                console.log(err);
                alert('Something went wrong, sorry :(');
            })
            .then(res => res.json())
            .then(parsedRes => {
                const habits = [];
                for (let key in parsedRes) {
                    habits.push({
                        ...parsedRes[key],
                        key: key
                    })
                }
                console.log(habits);
                dispatch(setHabits(habits));
            })
    }
}

export const setHabits = habits => {
    return {
        type: SET_HABITS,
        habits: habits
    }
}

MY REDUCER

const habitsReducer = (state = initialState, action) => {
  switch (action.type) {
  case SET_HABITS:
      return {
        ...state,
        habits: action.habits
      }
 default:
      return state;
  }
};

export default habitsReducer;

2

2 Answers

0
votes

you mapStateToProps is wrong. change your mapStateToProps to below

const mapStateToProps = state => {
    console.log(state.habits.habits)
    // returns an array with my two test objects included... [ Object, Object]
    return {
        //Change state.habits.habits to state.habitsReducer 
        habits: state.habitsReducer 
    }
}
0
votes

Thanks for the answer Malik, I realized that my issue was where I was calling console.log. The ComponentDidMount function properly assigned the state to props, however, it was only accessible in the render() function... once the component mounted and rendered, the props were available for use.

Hope this helps people!