I'm using useSelector instead of mapStateToProps function in my functional component called NavBar.js. When I run the program, I see this error in the console:
"Failed prop type: The prop auth
is marked as required in Navbar
, but its value is undefined
."
How should I solve it?
import React from 'react';
import { Link, withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect, shallowEqual, useSelector } from 'react-redux';
import { logoutUser } from '../../actions/authActions';
import { clearCurrentProfile } from '../../actions/profileActions';
const Navbar = (props) => {
const selectedData = useSelector((state) => state, shallowEqual)
const { isAuthenticated, user } = selectedData.auth;
return(
//Code......
)
}
Navbar.propTypes = {
logoutUser: PropTypes.func.isRequired,
clearCurrentProfile: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
};
export default withRouter(connect(null, { logoutUser, clearCurrentProfile })(Navbar));
The problem is you are no longer mapping the state to props but your component is still expecting the prop. To solve this problem, you need to remove auth
from propTypes
.
Navbar.propTypes = {
logoutUser: PropTypes.func.isRequired,
clearCurrentProfile: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired // this is the problem
};
Another unrelated issue I am seeing is you're using connect
to map the action creators to props. I'd suggest removing the use of connect
entirely by using useDispatch()
to dispatch your actions. Learn more