简体   繁体   中英

OnClick hook call - React

I need to execute a graphQL query so my users can log out. Ideally, they would click a logout button and the query would execute, signing them out. However, it's not that easy.

Here's my code so far:

const LOGOUT = gql`
  mutation Logout {
    logout
  }
`;

const LogoutButton = (props) => {
  const logout = () => {
    useMutation<Record<string, any>>(LOGOUT);
  };

  return (
    <button onClick={logout}>Logout</button>
  )
};

I'm getting the following error message: Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

I'm sorry for such a rookie question, but I'm stuck. I appreciate any advice.

The error is the answer. Your component here is not a functional component. It's likely you forgot to wrap your logic in to a component. Try this:

const LOGOUT = gql`
  mutation Logout {
    logout
  }
`;

const LogoutButton = (props) => {
  const logout = () => {
    useMutation<Record<string, any>>(LOGOUT);
  };

  return (
    <button onClick={logout}>Logout</button>
  )

};

Then call LogoutButton where you want your button to appear.

Note: I didn't list imports here as I'm assuming you know what you need to import to get this to work.

Try something like this:

const LOGOUT = gql`
  mutation Logout {
    logout
  }
`;

const LogoutButton = (props) => {
  const [logout] = useMutation<Record<string, any>>(LOGOUT);

  return (
    <button onClick={logout}>Logout</button>
  )

};

A hook, aka something that begins with use...() , is always meant to be placed top-level in your functional component, never within a callback. In this case, useMutation already returns your function (specifically, wrapped inside an array).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM