Apollo Client: Can't put ReactHook after Conditional, but React Hook needs data available only after conditional?

Viewed 58

Order of Operations issues it seems.

  1. Can't use a React Hook after a Conditional as I get this error:

    Error: Rendered more hooks than during previous render

  2. This React Hook is 3rd party and can't change it. This React Hook needs data that is only available after the conditional...so I get another error of data not defined

  3. Ok, how about declare a new variable (empty array) to put in 3rd party React hook before conditional? Then after conditional reassign with data that shows up. Doesn't work either... as I get error that it is using the same key...well because the 3rd party hook is getting an empty array variable first. What do I do?

   import { libraryHook } from '3rd party'
   import { useQuery } from '@apollo/client'
    
    const myComponent = () => {
      const {loading, error, data } = useQuery(MY_QUERY, { variables: {someVariable: fromDatabase}
      
      const { 3rdpartyVariable } = libraryHook(data);

      // Hook needs to be above conditional so I don't get error,
      //but data only available after conditional.

      if (loading) return <div>Loading...</div>;
      if (error) return <div>{error.message}</div>;
    
    console.log(data);
    
    return(
      <div>
        {data}
      </div>
    )
    
    }
    
    export default myComponent;```
1 Answers

There is another hook called useLazyQuery that can be used in this case, it provides you a function that can be called to execute your query. This is how you can do it

import { gql, useLazyQuery } from "@apollo/client";

const GET_GREETING = gql`
  query GetGreeting($language: String!) {
    greeting(language: $language) {
      message
    }
  }
`;

function Hello() {
  const [loadGreeting, { called, loading, data }] = useLazyQuery(
    GET_GREETING,
    { variables: { language: "english" } }
  );
  if (called && loading) return <p>Loading ...</p>
  if (!called) {
    return <button onClick={() => loadGreeting()}>Load greeting</button>
  }
  return <h1>Hello {data.greeting.message}!</h1>;
}

Refer Docs

Related