An open API service indexing awesome lists of open source software.

https://github.com/freckle/resource-status-js


https://github.com/freckle/resource-status-js

Last synced: 8 months ago
JSON representation

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)