0

I am trying to run a simple graphql like this. I want to display all data fetched on the screen (for now the console.log would also work). However, everytime I click the button, I get the invalid hook issue and my page crashes.

I checked this :https://reactjs.org/warnings/invalid-hook-call-warning.html but I don't think i am doing any of these things wrong.

const ShowUsersQuery = gql`
query {
  users {
    nodes {
      id, firstName, email
    }
    totalCount
  }
}`;

function FindUsers() {
  const { loading, error, data } = useQuery(ShowUsersQuery);
  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;
  console.log('Data: ', data.users.nodes.firstName);
}

export default function UserSearchPage(){
  const [criteria, setCriteria] = useState('');
  const [searchItem, setSearchItem] = useState('');
  return (
    <div>
      <PermanentDrawerLeft></PermanentDrawerLeft>
      <div className='main-content'>
          <button 
          onClick={FindUsers}
          >HELLO</button>
            </div>
          )
    </div>
  );
}
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • 1
    You're breaking the first [rule of hooks](https://reactjs.org/docs/hooks-rules.html): _"Only Call Hooks at the Top Level"_ – Emile Bergeron Mar 03 '20 at 15:44
  • Oh I assumed it was for within a single function. Could you suggest an alternative? @EmileBergeron –  Mar 03 '20 at 15:59
  • also, the duplicate question doesn't really help me especially since I am using hooks instead of components. Would appreciate if you could reopen it @EmileBergeron –  Mar 03 '20 at 16:00
  • Also, my code is in typescript, which is why I added the tag. @EmileBergeron –  Mar 03 '20 at 16:13
  • 1
    You should use the `useLazyQuery` hook as shown [in the linked post](https://stackoverflow.com/a/57887760/6024220). Check the docs for correct usage. The fact that you're using TypeScript is irrelevant to your issue. – Daniel Rearden Mar 03 '20 at 16:23

0 Answers0