Trying call useQuery in function with react-apollo-hooks

42,209

Solution 1

useQuery is a declarative React Hook. It is not meant to be called in the sense of a classic function to receive data. First, make sure to understand React Hooks or simply not use them for now (90% of questions on Stackoverflow happen because people try to learn too many things at once). The Apollo documentation is very good for the official react-apollo package, which uses render props. This works just as well and once you have understood Apollo Client and Hooks you can go for a little refactor. So the answers to your questions:

How do I call useQuery multiple times?

You don't call it multiple times. The component will automatically rerender when the query result is available or gets updated.

Can I call it whenever I want?

No, hooks can only be called on the top level. Instead, the data is available in your function from the upper scope (closure).

Your updateInformation should probably be a mutation that updates the application's cache, which again triggers a rerender of the React component because it is "subscribed" to the query. In most cases, the update happens fully automatically because Apollo will identify entities by a combination of __typename and id. Here's some pseudocode that illustrates how mutations work together with mutations:

const GET_USER_LIST = gql`
  query GetUserList {
    users {
      id
      name
    }
  }
`;

const UPDATE_USER = gql`
  mutation UpdateUser($id: ID!, $name: String!) {
    updateUser(id: $id, update: { name: $name }) {
      success
      user {
        id
        name
      }
    }
  }
`;

const UserListComponen = (props) => {
  const { data, loading, error } = useQuery(GET_USER_LIST);
  const [updateUser] = useMutation(UPDATE_USER);

  const onSaveInformation = (id, name) => updateUser({ variables: { id, name });

  return (
    // ... use data.users and onSaveInformation in your JSX
  );
}

Now if the name of a user changes via the mutation Apollo will automatically update the cache und trigger a rerender of the component. Then the component will automatically display the new data. Welcome to the power of GraphQL!

Solution 2

From apollo docs

When React mounts and renders a component that calls the useQuery hook, Apollo Client automatically executes the specified query. But what if you want to execute a query in response to a different event, such as a user clicking a button?

The useLazyQuery hook is perfect for executing queries in response to events other than component rendering

I suggest useLazyQuery. In simple terms, useQuery will run when your component get's rendered, you can use skip option to skip the initial run. And there are some ways to refetch/fetch more data whenever you want. Or you can stick with useLazyQuery

E.g If you want to fetch data when only user clicks on a button or scrolls to the bottom, then you can use useLazyQuery hook.

Solution 3

There's answering mentioning how useQuery should be used, and also suggestions to use useLazyQuery. I think the key takeaway is understanding the use cases for useQuery vs useLazyQuery, which you can read in the documentation. I'll try to explain it below from my perspective.

useQuery is "declarative" much like the rest of React, especially component rendering. This means you should expect useQuery to be called every render when state or props change. So in English, it's like, "Hey React, when things change, this is what I want you to query".

for useLazyQuery, this line in the documentation is key: "The useLazyQuery hook is perfect for executing queries in response to events other than component rendering". In more general programming speak, it's "imperative". This gives you the power to call the query however you want, whether it's in response to state/prop changes (i.e. with useEffect) or event handlers like button clicks. In English, it's like, "Hey React, this is how I want to query for the data".

Solution 4

You can use fetchMore() returned from useQuery, which is primarily meant for pagination.

const { loading, client, fetchMore } = useQuery(GET_USER_LIST);
const submit = async () => {
    // Perform save operation

    const userResp = await fetchMore({
      variables: {
          // Pass any args here
      },
      updateQuery(){

      }
    });
    console.log(userResp.data)
  };

Read more here: fetchMore

You could also use useLazyQuery, however it'll give you a function that returns void and the data is returned outside your function.

const [getUser, { loading, client, data }] = useLazyQuery(GET_USER_LIST);
const submit = async () => {
    const userResp = await getUser({
      variables: {
        // Pass your args here
      },
      updateQuery() {},
    });
    console.log({ userResp }); // undefined
  };

Read more here: useLazyQuery

Solution 5

You can create a reusable fetch function as shown below:

// Create query
const query = `
    query GetUserList ($data: UserDataType){
        getUserList(data: $data){
          uid,
          first_name
        }
    }
`;


// Component
export const TestComponent (props) {

  const onSaveInformation = async () => {
  
    // I want to call useQuery once again.  
    const getUsers = await fetchUserList();
  }
  

  // This is the reusable fetch function.
  const fetchUserList = async () => {

      // Update the URL to your Graphql Endpoint.
      return await fetch('http://localhost:8080/api/graphql?', {
      
          method: 'POST',
          headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json',
          },
          body: JSON.stringify({
              query,
              variables: { 
                 data: {
                    page: changePage,
                    pageSize: 10,
                  },
              },
          })
      }).then(
            response => { return response.json(); }  
       ).catch(
            error => console.log(error) // Handle the error response object
      );
  }

  return (
    <h1>Test Component</h1>
  );
  
}
Share:
42,209

Related videos on Youtube

ko_ma
Author by

ko_ma

Updated on July 09, 2022

Comments

  • ko_ma
    ko_ma almost 2 years

    I want to call useQuery whenever I need it,

    but useQuery can not inside the function.

    My trying code is:

    export const TestComponent = () => {
    ...
      const { data, loading, error } = useQuery(gql(GET_USER_LIST), {
        variables: {
          data: {
            page: changePage,
            pageSize: 10,
          },
        },
      })
      ...
      ...
      const onSaveInformation = async () => {
        try {
          await updateInformation({...})
          // I want to call useQuery once again.
        } catch (e) {
          return e
        }
    }
    ...
    

    How do I call useQuery multiple times?

    Can I call it whenever I want?

    I have looked for several sites, but I could not find a solutions.

  • Lauris Kuznecovs
    Lauris Kuznecovs over 4 years
    In case somebody still didnt get a full picture, here is quite nice example. ultimatecourses.com/blog/…
  • Ash Singh
    Ash Singh about 4 years
    This answer should have been the accepted answer according to the title of the post. Let me upvote it.
  • xadm
    xadm over 3 years
    not true that it (useQuery) can't be stopped ....there is a 'skip' option
  • JAvAd
    JAvAd about 3 years
    refetch() is not refresh or reload , refetch when parameter are same with before call load from cash not from server
  • Sam
    Sam over 2 years
    Thank you for the description. I just do not get how this function could be rendered. The only way that a functional components being rendered are via its own state or props. But when I do console.log(props) it is empty but in the return it still re-render when the loading is false