https://github.com/freckle/resource-status-js
https://github.com/freckle/resource-status-js
Last synced: 8 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/freckle/resource-status-js
- Owner: freckle
- License: mit
- Created: 2023-03-10T19:21:14.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-05-03T22:58:25.000Z (about 3 years ago)
- Last Synced: 2024-04-13T21:57:06.071Z (about 2 years ago)
- Language: TypeScript
- Size: 979 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Resource Status
Defines the `ResourceStatusT` type and utilities operating on this type.
## Install
```sh
yarn add @freckle/resource-status
```
## Versioning and release process
See [RELEASE.md](./RELEASE.md).
## `ResourceStatusT`
Wraps data from a resource `R` with metadata to describe the status of accessing
and updating the data. The `status` field can be used to react accordingly:
```ts
type Props = {resource: ResourceStatusT<{username: string}>}
const UserView = ({resource}: Props) => {
switch (resource.status) {
case 'idle':
return
User has not been loaded
case 'loading':
return Loading user
case 'reloading':
return User: {resource.data.username} (reloading)
case 'error':
return (
Error loading user:
{JSON.stringify(resource.error)}
)
case 'complete':
return User: {resource.data.username}
case 'updating':
return User: {resource.data.username} (pending update)
case 'updating-error':
return (
Error updating user {resource.data.username}:
{JSON.stringify(resource.error)}
)
default:
return exhaustive(resource)
}
}
```
## Utilities
Utilities are defined to make operating on a resource status.
### `maybeResourceData(resource)`
Returns the underlying `resource.data` if it exists.
### `fromMaybeResourceData(resource, default)`
Returns the underlying `resource.data` if it exists, or `default` otherwise.
### `isFetching(resource)`
Returns `true` when a `resource` is loading or reloading.
### `updateResource(resource, updateFn)`
Performs `updateFn(resource.data)` if there exists data in the resource, and
returns a new `resource`. This is convenient for reducer-style updates:
```ts
type State = ResourceStatusT<{username: string; token: string}>
type Action =
| {type: 'USER_UPDATE_REQUEST'}
| {type: 'USER_UPDATE_RESPONSE'; data: {username: string}}
const reducer = (state: State, action: Action) => {
switch (action.type) {
case 'USER_UPDATE_REQUEST':
// ...
case 'USER_UPDATE_RESPONSE':
return updateResource(state, user => ({
...user,
username: action.data.username
}))
}
}
```
---
[LICENSE](./LICENSE)