1
votes

Not able to access the redux store current state in a Class component.

It shows up console error

Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.

When I tried to implement the same using a function component with useSelector and useDispatch, everything works as expected. What has gone wrong over here?

reducer.js

let initialState={
    count:0
}

const reducer=(state=initialState,action)=>{
    switch(action.type){
        case ADD_INCREMENT:
            return {
                ...state,
                count:state.count+1
            };
        default: return state;
    }
}

export default reducer;

action.js

const Increment=()=>{
    return {
        type:ADD_INCREMENT
    }
} 

store.js

import reducer from './reducer';

const store=createStore(reducer);

export default store;

Class Component

 import { connect } from 'react-redux';
    
    const mapStateToProps=state=>{
        return {
            count:state.count
        }
    }

const mapDispatchToProps=(dispatch)=>{
    return {
        count:()=>dispatch(action.Increment())
    }
}
    
    class Orders extends Component {
        render() {
            return (
                <div>
                    <h1>Count: {this.props.count} </h1>
                </div>
            );
        }
    }
    
    export default connect(mapStateToProps,mapDispatchToProps)(Orders);

In App.js the entire container is wrapped with Provider and store is passed as props

1

1 Answers

0
votes

Issue

You've named your state and your action both count, the latter is the one injected as a prop.

const mapStateToProps = state => {
    return {
        count: state.count  // <-- name conflict
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        count: () => dispatch(action.Increment()) // <-- name conflict
    }
}

Solution

Provide different names, count for the state, maybe increment for the action.

const mapStateToProps = state => ({
  count: state.count,
});

const mapDispatchToProps = (dispatch) => ({
  increment: () => dispatch(action.Increment())
})