aribouius / jsonapi-react

A minimal JSON:API client and React hooks for fetching, updating, and caching remote data.
MIT License
149 stars 28 forks source link

clear error state between mutate calls #3

Closed bargar closed 4 years ago

bargar commented 4 years ago

Good stuff, love the api!

Question on useMutation hook:

We're leveraging the mutate function provided by useMutation. I've been testing to ensure that our UI responds correctly to errors/error state changes on repeated calls to the same instance of mutate.

If, say, multiple calls result in different 422 errors (e.g. the user corrects some form input and resubmits, but other validations still fail), the state reflects that correctly, yielding only the latest errors returned from the api.

However, if one submit results in 422 errors and a subsequent one results in a 500 (returned in error, not errors), the state now includes both the new error and the old errors, even though the server has only returned the 500.

Similarly, once a 500 has been returned via error, even when that error is resolved (e.g. temporary server problem), it continues to be reflected in the state on subsequent calls to mutate.

Seems to me that the error/errors state should be cleared at the start of each call to mutate. In this way, each call starts from a clean error state, and only the latest errors returned from the api will be reflected upon call completion.

This would mean removing the following line in useMutation:

    setState(prev => ({
      ...prev, <---- remove this line
      isLoading: true,
      promise,
    }))

https://github.com/aribouius/jsonapi-react/blob/master/src/hooks.js#L180

Thoughts? Happy to submit a PR if helpful.

aribouius commented 4 years ago

Hey @bargar thanks for catching that!

The previous result actually gets merged in to retain any stored result from previous mutations, as well as local data state (there's a undocumented setData method that gets returned from useMutation that lets you use the hook as a state container).

I added a fix for the issue, see https://github.com/aribouius/jsonapi-react/commit/712a4a1d6ba885eefe861873a740bdea7092225b, and published a new version v0.0.14.

bargar commented 4 years ago

@aribouius gotcha. Nice fix and speedy to boot. Our use case is working well against the new version.

Thanks and be well!