skip to Main Content

I have two graphql queries first one is getUser and second one is getChatHistory. I want getChatHistory to execute only after getUser is executed and user details are fetched.

export const getChatHistory = gql`{
   chatHistory {
     title
   }
  }
`;

export const getUser = gql`{
   user {
     name
     email
   }
  }
`;

const Home = ()=> {
  const {loading: chatLoading,error:chatError,data:chatData}=useQuery(getChatHistory);
  const {data:userData} = useQuery(getUser);
  ...

2

Answers


  1. You can’t do that in a single component using useQuery since it’s a hook and a hook can’t be called conditionally – make a separate nested component that grabs the chat history and don’t render it until you’ve got the user.

    Login or Signup to reply.
  2. It is possible. Based on useQuery hook signature
    const { loading, error, data } = useQuery(getChatHistory);
    I assume you are using apollo-client? If so, useQuery has skip option, designed for the cases like this.
    Here is how you can use it to start fetching chat history only after user in a single component:

    export const getChatHistory = gql`{
       chatHistory {
         title
       }
      }
    `;
    
    export const getUser = gql`{
       user {
         name
         email
       }
      }
    `;
    
    const Home = ()=> {
      const { data: userData } = useQuery(getUser);
      const {
        loading: chatLoading,
        error: chatError,
        data: chatData
      } = useQuery(getChatHistory, {
        // will not start fetching untill user is present
        skip: !userData?.user // or !userData?.getUser?.user depends on the response shape
      });
      ...
    
    

    getChatHistory won’t start fetching until user is fetched.

    For other clients:

    • In urql similar option called pause.
    • tanstack-query has enabled.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search