React error saying Objects are not valid as react child

Viewed 103

I am getting the [Error: Objects are not valid as a React child (found: object with keys {counter, num}). If you meant to render a collection of children, use an array instead.] error for the below code :

const initialState = {
    counter: 0,
    num : 0
}
const counterReducer = (state = initialState, action) => {
    switch(action.type){
        case "INCREMENT":
            {
                return {
                    ...state,
                    counter: state.counter + action.payLoad
                }
            }
            case "DECREMENT":
                return {
                    ...state,
                    counter: state.counter - action.payLoad
                }
        default:
            {
                return state;
            }
    }
}
export default counterReducer;

If I do like below everything working fine:

const counterReducer = (state = 0, action) => {
    switch(action.type){
        case "INCREMENT":
            return  state + action.payLoad;
        case "DECREMENT":
            return state - action.payLoad;
        default:
            {
                return state;
            }
    }
}

export default counterReducer;
2 Answers

You probably try to render somewhere the counter? Your default case returns the entire object, instead of just state.counter. Try it like this:

const counterReducer = (state = initialState, action) => {
switch(action.type){
    case "INCREMENT":
        {
            return {
                ...state,
                counter: state.counter + action.payLoad
            }
        }
        case "DECREMENT":
            return {
                ...state,
                counter: state.counter - action.payLoad
            }
    default:
        {
            return state.counter;
        }
    }
}

Or in the component where you render it access the object property state.counter

There's nothing wrong with the reducer you've written.

Without the corresponding component code and based on the error you're seeing, it seems that you're using the entire state object ({ counter: 0, num: 0 }, for example) within the React component that's using the state from this reducer.

Replacing the object ({ counter: 0, num: 0 }, from the above example) with just the counter value (obj.counter) should get it working

Related