• Stars
    star
    1,792
  • Rank 25,024 (Top 0.6 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 6 years ago
  • Updated 11 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

๐Ÿ’ Composable Promises & Promises as components

vue-promised Build Status npm package coverage thanks

Handle your promises with style ๐ŸŽ€

Help me keep working on Open Source in a sustainable way ๐Ÿš€. Help me with as little as $1 a month, sponsor me on Github.

Silver Sponsors

Vue Mastery logo Vuetify logo

Bronze Sponsors

Storyblok logo


Installation

npm install vue-promised
# or
yarn add vue-promised

If you are using Vue 2, you also need to install @vue/composition-api:

yarn add @vue/composition-api

Motivation

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>

๐Ÿ‘‰ Compare this to the version using Vue Promised that handles new promises.

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

Check the Changelog for breaking changes. v2 exposes the same Promised and a new usePromise function on top of that.

Usage

Composition API

import { Promised, usePromise } from 'vue-promised'

Vue.component('Promised', Promised)
export default {
  setup() {
    const usersPromise = 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>

Note the pending slot will by default, display after a 200ms delay. This is a reasonable default to avoid layout shifts when API calls are fast enough. The perceived speed is also higher. You can customize it with the pendingDelay prop.

The pending slot can also receive the data that was previously available:

<Promised :promise="usersPromise">
  <template v-slot:pending="previousData">
    <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

Sometimes, you need to customize how things are displayed rather than what is displayed. Disabling a search input, displaying an overlaying spinner, etc. Instead of using multiple slots, you can provide one 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: is true while the promise is in a pending status. Becomes false once the promise is resolved or rejected. It is reset to true when the promise prop changes.
  • isRejected is false. Becomes true once the promise is rejected. It is reset to false when the promise prop changes.
  • isResolved is false. Becomes true once the promise is resolved. It is reset to false when the promise prop changes.
  • isDelayElapsed: is true once the pendingDelay is over or if pendingDelay is 0. Becomes false after the specified delay (200 by default). It is reset when the promise prop changes.
  • data: contains the last resolved value from promise. This means it will contain the previous succesfully (non cancelled) result.
  • error: contains last rejection or null if 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 | String

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

License

MIT

More Repositories

1

vim-vue

Syntax Highlight for Vue.js components
Vim Script
1,285
star
2

unplugin-vue-router

Next Generation file based typed routing for Vue Router
TypeScript
1,279
star
3

catimg

๐Ÿฆฆ Insanely fast image printing in your terminal
C
1,239
star
4

vue-mdc

Material web components for Vue.js
JavaScript
1,201
star
5

mande

<700 bytes convenient and modern wrapper around fetch with smart extensible defaults
TypeScript
1,105
star
6

vuexfire

Check
JavaScript
559
star
7

pinia-colada

๐Ÿน The smart data fetching layer for Pinia
TypeScript
453
star
8

vite-tailwind-starter

Starter using Vite + Tailwind for super fast prototyping
Vue
452
star
9

vuex-mock-store

โœ…Simple and straightforward Vuex Store mock for vue-test-utils
JavaScript
273
star
10

focus-trap-vue

Vue component to trap the focus within a DOM element
JavaScript
200
star
11

vue-plugin-template

๐Ÿš€ Solid foundation to start a Vue plugin with the best developer experience and a focus on performance
JavaScript
192
star
12

vue-router-mock

๐Ÿงช Easily mock routing interactions in your Vue apps
TypeScript
187
star
13

vue-local-scope

๐Ÿ–‡ Generate local scopes in templates to compute data from other scoped slots or simply to have variables in templates
JavaScript
168
star
14

vue-reactive-refs

Make $refs reactive so they can be used in computed properties and watchers
TypeScript
160
star
15

vue-ts-lib

Vue 3 library starter in TS with lint, auto release, changelog and tests
JavaScript
156
star
16

sounds-webpack-plugin

๐Ÿ”ŠNotify or errors, warnings, etc with sounds
JavaScript
124
star
17

vue-tweezing

๐Ÿ’ƒ Easy, customizable and automatic tweening nicely served in scoped slots
JavaScript
100
star
18

vue-compose-promise

๐Ÿ’ Promises using vue composition api
TypeScript
76
star
19

vue-coerce-props

Coerce props to whatever you want
JavaScript
75
star
20

vue-use-spring

๐Ÿ’ซ Naturally fluid animations for Vue
TypeScript
72
star
21

shapify

๐ŸŒ€Easily transform objects/rename keys with full TypeScript support
JavaScript
67
star
22

pinia-plugin-debounce

Config-based action debouncing made easy
TypeScript
64
star
23

markdown-it-custom-block

Handle custom blocks transformations for markdown-it
JavaScript
53
star
24

state-animation-demos

Demos for Vue.js amsterdam/roadtrip talk: State animations, getting them right
Vue
43
star
25

task-logger.sh

๐ŸŽจ shell library to log tasks with nice output. Supports zsh and bash
Shell
43
star
26

vue-router-view-transition

Properly time out-in transitions with scrollBehavior
JavaScript
40
star
27

vuefire-nuxt-example

Example project using VueFire with Nuxt
Vue
31
star
28

vue-prop-data-fallback

Vue mixin to support an optional prop by falling back to a local data
JavaScript
31
star
29

vuefire-emoji-panel

Nuxt + VueFire Demo code
TypeScript
30
star
30

size-check-action

A custom size action
TypeScript
28
star
31

2021-amsterdam-demos

Vue
25
star
32

rollit

๐ŸŒฏ Zero config js library bundling using rollup with support for Vue
JavaScript
24
star
33

talk-vuejs-and-typescript-a-complicated-relationship

Talk Vue.js and Typescript, a complicated relationship
21
star
34

unplugin-vue-router-demo

Demo for the talk "Stop writing your routes"
TypeScript
21
star
35

vue-recomputed

Recomputable computed properties
JavaScript
21
star
36

vuefire-vite-example

Example project using VueFire in a vite project
Vue
21
star
37

onlysponsors

Tracker for Only Sponsors
20
star
38

nuxt--vuefire-example-spark-plan

๐Ÿ”ฅ Nuxt + VueFire template to bootstrap your Firebase App
Vue
19
star
39

p-singleton

Ensure only one instance of a promise is created until rejected or resolved
JavaScript
19
star
40

clipboard-text

Simple and small copy-text-to-the-clipboard-utility with IE11 support
TypeScript
13
star
41

how2

Exercise building a scalable web app like how2 cli using Vue
JavaScript
12
star
42

nuxt--vuefire-example-blaze-plan

๐Ÿ”ฅ Nuxt + VueFire template to bootstrap your Firebase App with the Blaze plan
Vue
12
star
43

faked-promise

Create a fake promise that can be resolve and rejected programatically
JavaScript
11
star
44

jest-mock-warn

Mock console.log warn calls and assert their calls
JavaScript
11
star
45

lib-boilerplate-ts

personal boilerplate for a lib with ts
JavaScript
11
star
46

esm.dev

๐Ÿ‘จโ€๐Ÿ’ป my personal website
TypeScript
10
star
47

dotfiles

๐Ÿ“ My dotfiles
Vim Script
9
star
48

phaser-webpack-ts

Starter for Phaser 3 with Typescript, webpack and weback DLLPlugin
JavaScript
8
star
49

mocha-requirejs-boilerplate

JavaScript
7
star
50

paths.esm.dev

๐Ÿ›ฃ A Vue Router path debugger
Vue
7
star
51

mocha-css

A mocha stylesheet for the HTML reporter that let you append visual tests
CSS
7
star
52

eslint-config-posva

๐Ÿคบ Opinionated eslint set of rules with support for Vue
JavaScript
7
star
53

vitesse-unplugin-vue-router

Test repo for unplugin-vue-router + vitesse
TypeScript
6
star
54

minesweeper.rs

Learning project with Rust: Minesweeper
Rust
5
star
55

OUTDATED_nuxt-vuefire-example

wip
Vue
5
star
56

renovate-config

Renovate config for Open Source
5
star
57

vitepress-theme-nuxt-content

Vitepress theme imitating Nuxt Content
Vue
4
star
58

pinia-ssr-example-cw

TypeScript
4
star
59

instacraper

Scrap images from Instagram post
JavaScript
4
star
60

nuxt--vuefire-demo

Nuxt VueFire Demo
Vue
4
star
61

vercel-nuxt-example

Vue
3
star
62

vue-pinia-example

Created with CodeSandbox
JavaScript
3
star
63

vuefire-vitesse-example

Example of using VueFire with SSR
TypeScript
3
star
64

vuefire-core

mirror to test something with codecov
JavaScript
3
star
65

bug-vue-loader-slot

Vue
2
star
66

store-code-split-demo

demo to showcase ideal codesplit for a store like Vuex
JavaScript
2
star
67

bug-report-vca

JavaScript
2
star
68

nuxt-composition-api-185

Vue
2
star
69

configure-script

โšก Simple script to generate Makefiles for your project. It's mainly aimed for C/C++ but can be adapted to other languages
Shell
2
star
70

vuefire-examples

Various examples showcasing vuefire/vuexfire
HTML
2
star
71

.github

Default .github folder
2
star
72

2d-collisions

Collision for 2D using the SAT theorem with Rectangles
C++
2
star
73

mangare-angular

๐Ÿ™ Download Manga in convenient formats!
JavaScript
1
star
74

mille-bornes

mille bornes card game for 2 players only with AI and online
CoffeeScript
1
star
75

slides

๐Ÿ“ข Talks I have given somewhere, sometime
HTML
1
star
76

blog.esm.dev

Vue
1
star
77

awesome-latex-workspace

๐Ÿ“‘ Watcher + commit based diff generator
Shell
1
star
78

vue-merge-options

Helpers to merge vue custom options
1
star
79

bcn-marfeel-demo

Demo for the meetup @marfeel the 19/07/2018
Vue
1
star
80

bug-report-nuxt-plugin

TypeScript
1
star
81

lerna-test

Testing things with lerna
JavaScript
1
star
82

imag-utils

Scripts ou autres infos utiles ร  l'Ensimag
JavaScript
1
star
83

Rndm

Random number generation for vim
Vim Script
1
star
84

portfolio

1
star
85

planet-noise

Test to generate planet terrain using libnoise. SFML to render the image
C++
1
star
86

app-dep-test-renovate

JavaScript
1
star
87

vue-mdc.js.org

Documentation for vue-mdc
JavaScript
1
star
88

literate-couscous

1
star
89

lab-vue-getting-started

tech.io lab
JavaScript
1
star
90

tetris

โฌ› A simple engine of tetris that can be used along with another printing system
C
1
star
91

pretty-hrtime.sh

๐Ÿ•’ Pretty High Resolution Time in shell
Shell
1
star
92

nuxt--vuefire-repro-template

Nuxt VueFire template for reproductions
Vue
1
star
93

posva

๐ŸŒฎ๐ŸŒฎ๐ŸŒฎ
1
star
94

app-dep-test

JavaScript
1
star
95

test-pr-lib

JavaScript
1
star
96

MangaDown

Allow to download mangas from websites using a parsing file
C++
1
star
97

gotta-go-fast-vim

๐ŸŽ Language agnostic starter kit for vim
Shell
1
star
98

pinia.esm.dev-redirect

Redirect site from pinia.esm.dev to pinia.vuejs.org
1
star
99

hydrogen

iGam4ER
JavaScript
1
star