Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Hook "useSelector" is called in function

I cannot figure out what going on with "useSelector" I need little help, please.

ERROR

React Hook "useSelector" is called in function "render_user" which is neither a React function component or a custom React Hook function

class Navigationbar extends Component {

  onLogoutClick = e => {
    e.preventDefault();
    this.props.logoutUser(); //this.props.
  };

  render() {
      const render_user = () => {

        const auth = useSelector(state => state.auth); Error Message is here
        //More Code Here
      );
    };
  } 

Navigationbar.propTypes = {
  logoutUser: PropTypes.func.isRequired,
  auth: PropTypes.object.isRequired
};

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

export default connect(
  mapStateToProps,
  { logoutUser }
)(Navigationbar);
like image 558
bpdg Avatar asked Sep 03 '19 01:09

bpdg


3 Answers

The error is due to the fact that you violated the rules of hooks:

  • Only Call Hooks at the Top Level
  • Only Call Hooks from React Functions

Violations:

  1. useSelector() is not called in top-level. It is called in render_user() in render() (i.e nested function).
  2. useSelector() is part of a class component, Navigationbar

You can extract a component to follow the rules of hooks and make use of useSelector:

function User() { // Rule 2: call hooks in function component
  const auth = useSelector(state => state.auth); // Rule 1: call hooks in top-level
  return <>{auth}</>
}

class Navigationbar extends Component {

  render_user() {
    if (props.authenticated) {
      return <User />
    }
    // not yet authenticated
    // do something else
  }

  render() {
    return <>{this.render_user()}</>
  }
}
like image 183
Joseph D. Avatar answered Sep 20 '22 10:09

Joseph D.


If you are using TypeScript and (obviously) a functional component. Make sure your component name begins with a capital letter and not a lowercase letter.

like image 40
Amir Ali Avatar answered Sep 21 '22 10:09

Amir Ali


useSelector is new hook that is added by react-redux after the addition of new Hooks API to react.

These hooks can only be used in function component

like image 44
Shivang Gupta Avatar answered Sep 21 '22 10:09

Shivang Gupta