Starbax
Starbax

Reputation: 59

how to call 2 times when data in graphql react?

loadGreeting () is not caused by another time when changes props.currentStore

  const [loadGreeting, { called, loading, data }] = useLazyQuery(
      GET_COOKIES,
     { context: {
        headers: {
          "x-request-shop-id": props.currentStore ? props.currentStore.id : ""
        },
      }},
  );

  useEffect(() => {
    if (props.currentStore.id) {
      loadGreeting();// here it comes a change but does not cause other data props.correntStore
  }
  }, [props.currentStore ]);

Upvotes: 1

Views: 3256

Answers (2)

Long Nguyen Duc
Long Nguyen Duc

Reputation: 1325

By default, the query uses cache-first as fetch policy. So ApolloClient will not query data on the server-side when they are available on the cache.

You should change fetch policy to cache-and-network then the ApolloClient will query the data on the server-side, even they are available on the cache or not.

const [loadGreeting, { called, loading, data }] = useLazyQuery(GET_COOKIES, {
  context: {
    headers: {
      'x-request-shop-id': props.currentStore ? props.currentStore.id : ''
    }
  },
  fetchPolicy: 'cache-and-network'
});

Upvotes: 4

Abhi Patel
Abhi Patel

Reputation: 224

useQuery or useLazyQuery 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 refactoring. 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).

Upvotes: -3

Related Questions