vue-promised

Handle your promises with style
π
Help me keep working on Open Source in a sustainable way
Silver Sponsors
Bronze Sponsors
Installation
npm install vue-promised
# or
yarn add vue-promisedMotivation
When dealing with asynchronous requests like fetching content through API calls, you may want to display the loading state with a spinner, handle the error and even hide everything until at least 200ms have been elapsed so the user doesn't see a loading spinner flashing when the request takes very little time. This is quite some boilerplate, and you need to repeat this for every request you want:
<template>
<div>
<p v-if="error">Error: {{ error.message }}</p>
<p v-else-if="isLoading && isDelayElapsed">Loading...</p>
<ul v-else-if="!isLoading">
<li v-for="user in data">{{ user.name }}</li>
</ul>
</div>
</template>
<script>
export default {
data: () => ({
isLoading: false,
error: null,
data: null,
isDelayElapsed: false,
}),
methods: {
fetchUsers() {
this.error = null
this.isLoading = true
this.isDelayElapsed = false
getUsers()
.then((users) => {
this.data = users
})
.catch((error) => {
this.error = error
})
.finally(() => {
this.isLoading = false
})
setTimeout(() => {
this.isDelayElapsed = true
}, 200)
},
},
created() {
this.fetchUsers()
},
}
</script>That is quite a lot of boilerplate and it's not handling cancelling on going requests when fetchUsers is called again. Vue Promised encapsulates all of that to reduce the boilerplate.
Migrating from v1
Migrating to v2 from v1 should be doable in a small amount of time as the only breaking changes are some slots name and the way Promised component is imported.
Check releases notes to see the list of breaking changes
Usage
Composition API
import { usePromise } from 'vue-promised'
Vue.component('Promised', Promised)
export default {
setup() {
const userPromise = ref(fetchUsers())
const promised = usePromise(usersPromise)
return {
...promised,
// spreads the following properties:
// data, isPending, isDelayElapsed, error
}
},
}Component
Vue Promised also exposes the same API via a component named Promised.
In the following examples, promise is a Promise but can initially be null. data contains the result of the promise. You can of course name it the way you want:
Using pending, default and rejected slots
<template>
<Promised :promise="usersPromise">
<!-- Use the "pending" slot to display a loading message -->
<template v-slot:pending>
<p>Loading...</p>
</template>
<!-- The default scoped slot will be used as the result -->
<template v-slot="data">
<ul>
<li v-for="user in data">{{ user.name }}</li>
</ul>
</template>
<!-- The "rejected" scoped slot will be used if there is an error -->
<template v-slot:rejected="error">
<p>Error: {{ error.message }}</p>
</template>
</Promised>
</template>
<script>
export default {
data: () => ({ usersPromise: null }),
created() {
this.usersPromise = this.getUsers()
},
}
</script>The pending slot can also receive the data that was previously available:
<Promised :promise="usersPromise">
<template v-slot:pending="data">
<p>Refreshing</p>
<ul>
<li v-for="user in previousData">{{ user.name }}</li>
</ul>
</template>
<template v-slot="data">
<ul>
<li v-for="user in data">{{ user.name }}</li>
</ul>
</template>
</Promised>Although, depending on the use case, this could create duplication and using a combined slot would be a better approach.
Using one single combined slot
You can also provide a single combined slot that will receive a context with all relevant information. That way you can customize the props of a component, toggle content with your own v-if but still benefit from a declarative approach:
<Promised :promise="promise">
<template v-slot:combined="{ isPending, isDelayElapsed, data, error }">
<pre>
pending: {{ isPending }}
is delay over: {{ isDelayElapsed }}
data: {{ data }}
error: {{ error && error.message }}
</pre>
</template>
</Promised>This allows to create more advanced async templates like this one featuring a Search component that must be displayed while the searchResults are being fetched:
<Promised :promise="searchResults" :pending-delay="200">
<template v-slot:combined="{ isPending, isDelayElapsed, data, error }">
<div>
<!-- data contains previous data or null when starting -->
<Search :disabled-pagination="isPending || error" :items="data || []">
<!-- The Search handles filtering logic with pagination -->
<template v-slot="{ results, query }">
<ProfileCard v-for="user in results" :user="user" />
</template>
<!--
Display a loading spinner only if an initial delay of 200ms is elapsed
-->
<template v-slot:loading>
<MySpinner v-if="isPending && isDelayElapsed" />
</template>
<!-- `query` is the same as in the default slot -->
<template v-slot:noResults="{ query }">
<p v-if="error" class="error">Error: {{ error.message }}</p>
<p v-else class="info">No results for "{{ query }}"</p>
</template>
</Search>
</div>
</template>
</Promised>context object
isPending: istruewhile the promise is in a pending status. Becomesfalseonce the promise is resolved or rejected. It is reset totruewhen thepromiseprop changes.isDelayElapsed: istrueonce thependingDelayis over or ifpendingDelayis 0. Becomesfalseafter the specified delay (200 by default). It is reset when thepromiseprop changes.data: contains the last resolved value frompromise. This means it will contain the previous succesfully (non cancelled) result.error: contains last rejection ornullif the promise was fullfiled.
Setting the promise
There are different ways to provide a promise to Promised. The first one, is setting it in the created hook:
export default {
data: () => ({ promise: null }),
created() {
this.promise = fetchData()
},
}But most of the time, you can use a computed property. This makes even more sense if you are passing a prop or a data property to the function returning a promise (fetchData in the example):
export default {
props: ['id'],
computed: {
promise() {
return fetchData(this.id)
},
},
}You can also set the promise prop to null to reset the Promised component to the initial state: no error, no data, and pending:
export default {
data: () => ({ promise: null }),
methods: {
resetPromise() {
this.promise = null
},
},
}API Reference
usePromise
usePromise returns an object of Ref representing the state of the promise.
const { data, error, isPending, isDelayElapsed } = usePromise(fetchUsers())Signature:
function usePromise<T = unknown>(
promise: Ref<Promise<T> | null | undefined> | Promise<T> | null | undefined,
pendingDelay?: Ref<number | string> | number | string
): {
isPending: Ref<boolean>
isDelayElapsed: Ref<boolean>
error: Ref<Error | null | undefined>
data: Ref<T | null | undefined>
}Promised component
Promised will watch its prop promise and change its state accordingly.
props
| Name | Description | Type |
|---|---|---|
promise |
Promise to be resolved | Promise |
pendingDelay |
Delay in ms to wait before displaying the pending slot. Defaults to 200 |
`Number |
slots
All slots but combined can be used as scoped or regular slots.
| Name | Description | Scope |
|---|---|---|
pending |
Content to display while the promise is pending and before pendingDelay is over | previousData: previously resolved value |
| default | Content to display once the promise has been successfully resolved | data: resolved value |
rejected |
Content to display if the promise is rejected | error: rejection reason |
combined |
Combines all slots to provide a granular control over what should be displayed | context See details |

Formed in 2009, the Archive Team (not to be confused with the archive.org Archive-It Team) is a rogue archivist collective dedicated to saving copies of rapidly dying or deleted websites for the sake of history and digital heritage. The group is 100% composed of volunteers and interested parties, and has expanded into a large amount of related projects for saving online and digital history.
