Koushik ruidas
Koushik ruidas

Reputation: 71

React error saying Objects are not valid as react child

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;

Upvotes: 2

Views: 117

Answers (2)

Kul
Kul

Reputation: 1239

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

Upvotes: 1

maten
maten

Reputation: 586

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

Upvotes: 1

Related Questions