https://github.com/isthatcentered/use-promise-machine
React promises as a state machine. Tells you explicitly if your promise is PENDING || FULFILLED_DATA || FULFILLED_EMPTY || REJECTED
https://github.com/isthatcentered/use-promise-machine
Last synced: about 1 year ago
JSON representation
React promises as a state machine. Tells you explicitly if your promise is PENDING || FULFILLED_DATA || FULFILLED_EMPTY || REJECTED
- Host: GitHub
- URL: https://github.com/isthatcentered/use-promise-machine
- Owner: isthatcentered
- Created: 2019-05-07T12:14:28.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2020-11-02T04:38:06.000Z (over 5 years ago)
- Last Synced: 2024-04-25T19:02:28.637Z (about 2 years ago)
- Language: TypeScript
- Size: 538 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 14
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# usePromiseMachine
Because having to set `loading` and `error` and doing some `if (data)` for promises is boring 🙃.
## Features
- Know instantly which state your promise is in via `myPromise.state` *(-> `PENDING` || `FULFILLED_DATA` || `FULFILLED_EMPTY` || `REJECTED`)*
- Easily access the error or the data via `myPromise.error` or `myPromise.data`
- Don't bother guessing if you're getting back an empty container (`[]` or `{}`). If it's the case, `myPromise.state` will be `FULFILLED_EMPTY`
- No need to remember the existing states, they're all available via `usePromiseMachine.STATES.*`
- Simpler code, safe, 0 brain power required 🥳
## Install
```bash
npm i use-promise-machine -D
```
## Use
```typescript jsx
import { usePromiseMachine } from "use-promise-machine"
function _HomePage( props: {})
{
// (use useCallback if you're using an inline function to avoir infinite rendering)
const myFunctionThatReturnsAPromise = useCallback(() => fetch("/waffles")),
dataPromise = usePromiseMachine(myFunctionThatReturnsAPromise)
return (
{(() => {
switch ( dataPromise.state ) {
case usePromiseMachine.STATES.PENDING:
return Loading...
case usePromiseMachine.STATES.REJECTED:
return 💩 Something went wrong
// You can merge switch cases if you don't care about data or empty state
case usePromiseMachine.STATES.FULFILLED_DATA:
case usePromiseMachine.STATES.FULFILLED_EMPTY:
return
// will never be reached
default:
return null
}
})()}
)
}
```
## Fun facts
- You can access every state the promise can be in by using the `usePromise.STATES` variable.
- The `usePromise.STATES.FULFILLED_EMPTY` means your promise returns either an empty `array` or an empty `object`
## Learn more
Check the tests folder in `src/usePromise.spec.ts` or [tweet me 😉](https://twitter.com/isthatcentered)