relay-tools / relay-hooks

Use Relay as React hooks
https://relay-tools.github.io/relay-hooks/docs/relay-hooks.html
MIT License
540 stars 56 forks source link

Polling in `useQuery` hook not working #173

Closed quant-daddy closed 3 years ago

quant-daddy commented 3 years ago

I'm trying to poll in this query but I don't see it happening :) Am I doing something wrong? I tried with fetchPolicy network-only and without it but nothing seems to work!

const checkNewNotification = useQuery<SiteNav_NewNotificationCountQuery>(
    graphql`
      query SiteNav_NewNotificationCountQuery {
        viewer {
          id
          pendingNotificationsCount
        }
      }
    `,
    {},
    {
      networkCacheConfig: {
        poll: 5 * 1000,
        force: true,
      },
      // fetchPolicy: 'network-only',
      // skip: !isViewerLoggedIn,
    },
  );
morrys commented 3 years ago

Hi @skk2142, you probably have a problem with how you fetch. This polling example https://github.com/relay-tools/relay-hooks/pull/160/files#diff-fb6fe2a8b883627e56a2abde6c18d6e7d82b159becd54d1026fe4e1cb83d29dcR62 may help you.

quant-daddy commented 3 years ago

Thank you @morrys it's working now! For reference, this is my fetch query:

function getFetchQuery(
  apiUrl: RequestInfo,
  getHeaders: () => OutgoingHttpHeaders,
): FetchFunction {
  const headers = (getHeaders() as unknown) as Headers;
  const queryFetcher: FetchFunction = (operation, variables) => {
    const observable = Observable.create(sink => {
      fetch(apiUrl, {
        method: 'POST',
        headers,
        body: JSON.stringify({
          documentId: operation.id,
          operationName: operation.name,
          // query: operation.text,
          variables,
          // id: operation.id,
          // documentId:
        }),
      })
        .then(response => response.json())
        .then(data => {
          sink.next(data);
          sink.complete();
        })
        .catch(e => {
          console.error(e);
          sink.error(e);
        });
    });
    return observable;
  };
  return queryFetcher;
}