contiamo / restful-react

A consistent, declarative way of interacting with RESTful backends, featuring code-generation from Swagger and OpenAPI specs 🔥
MIT License
1.87k stars 109 forks source link

Poll with generated React hook data fetchers #308

Closed JakobEdding closed 3 years ago

JakobEdding commented 3 years ago

I'm using the restful-react import script to automatically generate data fetchers for React from an OpenAPI specification. So far, I haven't found a way to use the auto-generated data fetchers together with the Poll component. Instead, I can't use it and have to specify the path prop manually.

Is there a simple way to use the auto-generated data fetchers with the Poll component without having to manually specify the path prop and other props that are prone to change once the API changes? That would be a nice feature!

fabien0102 commented 3 years ago

https://github.com/contiamo/restful-react/blob/a62899dc53b5e98c712778d4438a02b504542358/src/scripts/tests/import-open-api.test.ts#L2088-L2154

For now we generate Poll component when the header prefer is specify on the specs (more information about this design decision here -> https://github.com/contiamo/restful-react#long-polling)

After, this is the "legacy" <Poll /> component, we don't have any equivalent in hook version. Polling is quite trivial in react hook so we usually add a small useEffect when we need some polling feature.

Example from our product:

// Poll data if no completedAt
  useEffect(() => {
    if (error) {
      return onError();
    } else if (data && !data.completedAt) {
      const timerId = window.setTimeout(() => refetch(), 1000);
      return () => window.clearTimeout(timerId);
    } else {
      return;
    }
  }, [data, refetch, error]);

So just call refetch with window.setTimeout().

JakobEdding commented 3 years ago

Thanks for the quick and helpful response! Specifying the prefer header in the backend specs and using the auto-generated Poll component does the job for me.