Gathering detailed insights and metrics for promistate
Gathering detailed insights and metrics for promistate
Gathering detailed insights and metrics for promistate
Gathering detailed insights and metrics for promistate
Manage promises in UI libraries such as React.js, Vue.js, Angular, Svelte, Alpine.js, etc.
npm install promistate
Typescript
Module System
Node Version
NPM Version
usePromistate improvements
Updated on Jan 24, 2022
Add delay option & isDelayOver field
Updated on Oct 22, 2020
Programmatically set error
Updated on Sep 13, 2020
listen API & React Hooks support
Updated on Jun 26, 2020
Add option to ignore stale promise loads + cancelling promises
Updated on Jun 25, 2020
Added timesSettled & resolve synchronous callbacks
Updated on Jan 22, 2020
TypeScript (98.71%)
JavaScript (1.29%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
16 Stars
65 Commits
1 Forks
1 Watchers
4 Branches
1 Contributors
Updated on Jan 18, 2025
Latest Version
1.7.3
Package Id
promistate@1.7.3
Unpacked Size
21.20 kB
Size
6.60 kB
File Count
8
NPM Version
8.1.2
Node Version
16.13.1
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
3
Easily manage promises in reactive JavaScript libraries and frameworks such as React.js, Vue.js, Angular, Svelte, Alpine.js, etc.
npm i promistate
1<template> 2 <div v-if="error">Whoops!</div> 3 <div v-else-if="isPending">loading...</div> 4 <div v-else-if="users.length === 0">no results...</div> 5 <UserList v-else :users="users" /> 6</template> 7 8<script> 9export default { 10 data() { 11 return { users: [], isPending: true, error: null } 12 }, 13 async created() { 14 const groupId = this.$route.params.groupId 15 this.isPending = true 16 try { 17 this.users = await fetch(`/api/${groupId}/users`).then(res => res.json()) 18 } catch(error) { 19 this.error = error 20 } 21 this.isPending = false 22 } 23} 24</script>
All state changes handled internally and exposed through a single object 👍.
1<template> 2 <div v-if="userPromise.error">Whoops!</div> 3 <div v-else-if="userPromise.isPending">loading...</div> 4 <div v-else-if="userPromise.isEmpty">no results...</div> 5 <UserList v-else :users="userPromise.value" /> 6</template> 7 8<script> 9import promistate from 'promistate' 10 11export default { 12 data: ({ 13 userPromise: promistate(groupId => fetch(`/api/${groupId}/users`).then(res => res.json())) 14 }), 15 created() { 16 this.userPromise.load(this.$route.params.groupId) 17 } 18} 19</script>
1import promistate from 'promistate' 2 3const userPromise = promistate(async function callback(id) { 4 return fetch('/api/user/' + id).then(res => res.json()) // any promise 5}) 6 7// later... 8console.log(userPromise.value) // null 9await userPromise.load(1) 10console.log(userPromise.value) // { id: 1, name: '...' }
The callback passed into promistate
gets executed once you call the "load" method.
Calling "promistate()" immediately returns an object that has the following properties.
(See below for react hook example)
field | description |
---|---|
load | A method to call the previously passed in callback. Arguments get propogated to callback |
value | Holds the resolved promise result |
isPending | Defines if promise is currently pending |
isDelayOver | Defines if promise is currently pending and the given delay (see configurations) has elapsed. |
timesSettled | counts how many times a promise was settled. Sometimes you want to wait until a promise was settled |
isEmpty | Defines if there is a result. Conveniently switches to false when promise is pending. isEmpty is true when the result is an empty array, empty object, null or undefined |
error | Error object in case promise was rejected |
reset | A method to reset all state (value, isEmpty, error, isPending) |
You can pass in arguments as needed
1const calculator = promistate(async function callback(num1, num2) { 2 return num1 + num2 3}) 4 5await calculator.load(1, 2)
"load" returns a status message about the promise. This can be either
This can be useful if you have to do more work after loading a promise. Note how there is no need to reach for this in the example at the top.
To avoid hardcoding these, you can import "PromistateStatus" from the library
1import promistate, { PromistateStatus } from 'promistate' 2 3const userPromise = promistate(() => fetch('...')) 4 5if (await userPromise.load() === PromistateStatus.RESOLVED) { 6 console.log("It's resolved!", userPromise.value) 7}
Pass configurations as the second argument
1import promistate from 'promistate' 2 3promistate(async function callback() { 4 return somethingAsync() 5}, { catchErrors: false, defaultValue: 42 })
key | type | default | use case |
---|---|---|---|
catchErrors | boolean | true | You already use something like an ErrorBoundary component for catching errors |
defaultValue | any | null | You already have a value at hand, or want to default it to an empty array, object, etc. |
ignoreStaleLoad | boolean | false | If you "load" while there is already a promise pending, this will ignore any stale promise results. By calling "reset" you can also cancel promises this way. |
ignoreLoadWhenPending | boolean | false | Prevent an event being fired twice e.g. when clicking a button. With this boolean set, while the first promise is still pending, subsequent loads would be ignored (not deferred!). When a subsequent load gets ignored, the "load" method returns the status "IGNORED" |
delay | number | 200 | Specifies after how many ms isDelayOver will be set to true. This is useful to avoid flashing loading spinners for fast requests. |
isEmpty | Function | undefined | Say, the result is { page: 1, items: [] } , the default "isEmpty" would always evaluate to false since a filled object is considered not empty. You can tweak the check like this: { isEmpty: value => value.items.length < 1 } |
listen | Function | undefined | Listen to any state changes. Useful for integrations in libraries like Svelte or React.js |
Usage with react differs in two ways
usePromistate
from promistate/lib/react
usePromistate
returns a tuple with the first value holding the state, and the second value holding all methods to update the state1import React from "react"; 2import { usePromistate } from "promistate/lib/react"; 3 4export default function App() { 5 const [todosPromise, todoActions] = usePromistate(somePromise); 6 // todosPromise.value, todosPromise.isPending, ... 7 // todoActions.load(), todoActions.reset(), todoActions.setValue('new Value') 8}
You can pass promistate options as the second argument usePromistate(somePromise, { defaultValue: "" })
,
and promise depedencies as the third argument usePromistate(somePromise, { }, [dep1, dep2])
.
To type the result of the promise you can make use of generics.
1import promistate from 'promistate' 2 3promistate<string>(async function callback() { 4 return 'updated' 5}, { defaultValue: 'initial' })
Absolutely.
As long as you don't use arrow functions you can access the state using this
.
1import promistate from 'promistate' 2 3promistate(async function callback() { 4 const result = await fetchItems(this.value.pageToken) 5 return { pageToken: result.pageToken, items: this.items.concat(result.items) } 6}, { 7 defaultValue: { items: [], pageToken: null }, 8 isEmpty: value => value.items.length < 1, 9})
Often times you want to reset the promise to its initial state. For this you can use the "reset" method.
But of course you can still mutate the value directly.
1import promistate from 'promistate' 2 3const promise = promistate(() => fetch('...')) 4 5promise.value // null 6promise.isEmpty // true 7 8promise.value = 2 9promise.isEmpty // false
If you use the react hook, do it like this instead:
1import { usePromistate } from 'promistate/lib/react' 2 3const [promise, actions] = usePromistate(() => fetch('...')) 4 5actions.setValue(2)
The same way you can also set the error programmatically.
1import promistate from 'promistate' 2 3const promise = promistate(() => fetch('...')) 4 5promise.error = new Error('internal error')
or with the react hook:
1import { usePromistate } from 'promistate/lib/react' 2 3const [promise, actions] = usePromistate(() => fetch('...')) 4 5actions.setError(new Error('internal error'))
fetch
?Sure, I personally use fetch-me-json.
1import promistate from 'promistate' 2import JSONFetch from 'fetch-me-json' 3 4const promise = promistate(() => JSONFetch.get('/api/...'))
npm run build
npm test
No vulnerabilities found.
Reason
no binaries found in the repo
Reason
6 existing vulnerabilities detected
Details
Reason
no SAST tool detected
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
license file not detected
Details
Reason
branch protection not enabled on development/release branches
Details
Score
Last Scanned on 2025-07-07
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More