9

I'm trying with the following code to execute urql useQuery only at once. But for some reason it is getting called on every re-render.

As per the docs https://formidable.com/open-source/urql/docs/basics/queries/#pausing-usequery this query should be paused initially on the render and it should only get executed when called from React.useEffect on mount.

const [{ fetching, data, error }, reExecute] = useQuery({
  query: INITIAL_CONFIG_QUERY,
  pause: true
});

React.useEffect(() => {
  reExecute();
}, []);

What could be the best way to execute query only at once using urql?

Ankit Balyan
  • 1,319
  • 19
  • 31

2 Answers2

8

Urql maintainer here, I'd assume if the component keeps remounting that something extra is happening. This hook should never make the wrapping component remount.

That being said you can always utilize the useClient hook to get the urql-client and then use client.query().toPromise() in that hook and use the returned result.

In your case this could be:

const MyComponent = () => {
  const client = useClient();
  useEffect(() => {
     client.query(
       INITIAL_CONFIG_QUERY
     ).toPromise().then(result => /* do something */)
  }, [])
}
jovi De Croock
  • 595
  • 2
  • 8
  • Thank you very much for answering. That'll solve the purpose. But I'm still not getting why my query gets executed if I've set paused option to `true`. does pause have a different use case than my understanding? – Ankit Balyan Jul 28 '20 at 18:48
  • I'm making this `useQuery` hook in the App Root Component, where it needs the initial config, which also sets the global context value after this query result, which cause the rerender. – Ankit Balyan Jul 28 '20 at 18:50
  • Another use case, I don't want to make a call on SSR (required xcsrf cookie and token to be present), so setting a pause option to `true`. but it is still making a call there. – Ankit Balyan Jul 28 '20 at 18:52
  • @AnkitBalyan this seems to work correctly for me https://codesandbox.io/s/nervous-butterfly-xwwh8?file=/src/components/Todos.js – jovi De Croock Jul 31 '20 at 14:27
0

This could be a urlq bug, but it also could be that your component is being unmounted and remounted every time the parent component rerenders.

To test this, add:

React.useEffect(() => {
  console.log("Component was mounted.");
}, []);

And see if the console.log statement gets printed more than once.

elijahcarrel
  • 3,787
  • 4
  • 17
  • 21
  • 1
    no, the component is rendering at a single time only. this useEffect hook gets called only once if I pass the empty dependency array. – Ankit Balyan Jul 30 '20 at 06:30