Reputation: 1735
I made a simple counter code using React JS with hooks and redux where I can increment/decrement counter on button clicks. When compiling I get error Error: Objects are not valid as a React child (found: object with keys {count}). If you meant to render a collection of children, use an array instead.
If I remove initialState and declare state=0
it works fine, but how can I execute this code successfully be keeping initialState ?
let initialState ={
count:0
}
const counter = (state=initialState,action)=>{
switch(action.type){
case 'INCREMENT': return {...state,count:state.count+1} ;
case 'DECREMENT':return {...state,count:state.count-1};
default: return state
}
}
export default counter
I consume the code in a component as mention below
const counter = useSelector(state=>state.counter)
<h3>{counter}</h3>
# note : some code parts are removed from this component for reader easiness
Upvotes: 0
Views: 248
Reputation: 544
It is an object so you should distruct the count property like this:
const {count } = useSelector(state=>state.counter)
<h3>{count}</h3>
Upvotes: 1
Reputation: 41893
The state.counter
isn't a primitive value, it's an object that you keep in your store under counter
field.
You can either go one level deeper:
const counter = useSelector(state => state.counter.count);
or directly refer to the count
value inside JSX:
<h3>{counter.count}</h3>
Upvotes: 3