'How can I use mapStateToProps to access the state of user in my redux store in class component

I am trying to convert a functional component to a class component. In the functional component, I import { useDispatch, useSelector } from 'react-redux'; and can access the dispatch and user state by:

const dispatch = useDispatch();
const user = useSelector(({ auth }) => auth.user);

Now I want to convert the component to a class component.

//userSlice.js (I omit unnecessary details)

import { createSlice } from '@reduxjs/toolkit';

const initialState = {
  role: [], // guest
  data: {
        displayName: 'xxxxxxx',
        email: '[email protected]'
  },
};

const setUserInReducer = (state, action) => {
    const user = {
        data: action.payload,
        role: [action.payload.role && action.payload.role.name || 'Guest'],
    }

    return user;
}

const userSlice = createSlice({
  name: 'auth/user',
  initialState,
  reducers: {
    setUser: setUserInReducer
  },
  extraReducers: {},
});

export const { setUser } = userSlice.actions;

export default userSlice.reducer;

//index.js for store

import { combineReducers } from '@reduxjs/toolkit';
import user from './userSlice';

const authReducers = combineReducers({
  user,
});

export default authReducers;

In my component, how can I access the user state to use it? I have something like:

//MyComponent.js

import { connect } from 'react-redux';
import { bindActionCreators } from '@reduxjs/toolkit';

class MyComponent extends Component {
    constructor(props) {
        super(props);
  }
  componentDidMount() {}

  render () {
    const user = this.props.user;
        return (
     console.log('user', user)
        )
  }
}


const mapStateToProps = (auth) => ({
  user: auth.user
})

function mapDispatchToProps(dispatch) {
  return bindActionCreators(
    dispatch
  );
}

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


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source