swr icon indicating copy to clipboard operation
swr copied to clipboard

[RFC] feat: Use a `status` enum to label the current stage of a SWR hook

Open icyJoseph opened this issue 3 years ago • 4 comments

Hi!

I've been using this library, and I've collected some feedback from colleagues or people I show this hook to.

One persistent subject is that, often developers want to derive the status of the hook, that is, is it loading? is it validating? is there a difference between them at all? is there any data, etc. Refer to: https://github.com/vercel/swr/discussions/563

I understand that we should open up discussions for these subjects first, but in this case it seemed best to talk over the code, because of the change itself and because I am short on bandwidth as of now.

I'll create a discussion thread and link both. Hopefully it doesn't create confusion. https://github.com/vercel/swr/discussions/1217

At the core of this PR, we derive a new key called status which can be loading, stale, error or validating.

In addition, I noticed that isValidating doesn't really settle on error cases. This might introduce breaking changes for users.

I included some tests which helpfully help understanding the subject matter of the feature.

Last but not least, more documentation is needed.

  • [ ] Documentation
  • [ ] Analyze possible breaking changes
  • [ ] More units tests
  • [ ] Infinite SWR

icyJoseph avatar Jun 15 '21 08:06 icyJoseph

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit b75282d09623f03912b4edf7032c64f99124a2bf:

Sandbox Source
SWR-Basic Configuration
SWR-States Configuration
SWR-Infinite Configuration
SWR-SSR Configuration

codesandbox-ci[bot] avatar Jun 15 '21 09:06 codesandbox-ci[bot]

As https://github.com/vercel/swr/issues/141#issuecomment-792077186 said, composing data, error and isValidating will result in 8 cases that make status enums hard to remeber for users. IMO it's better to keep automic for returned values and let users compose them flexibly on top of swr.

huozhi avatar Jun 16 '21 11:06 huozhi

Also worth noting, #1160 might help this. We can build a status middleware to attach a status enum to the SWR return object.

shuding avatar Jun 18 '21 23:06 shuding

It would be even better if the response was a tagged union:

type SWRResponse<Data, Error> =
  | {
    status: "loading"
    isValidating: boolean
    ...
  }
  | {
    status: "error"
    error: Error
    isValidating: boolean
    ...
  }
  | {
    status: "validating"
    data: Data
    isValidating: true
    ...
  }
  | {
    status: "stale"
    data: Data
    isValidating: false
    ...
  }

phaux avatar Aug 21 '22 18:08 phaux