vue-promise-snapshot
TypeScript icon, indicating that this package has built-in type declarations

1.1.3 • Public • Published

Vue logo

Vue Promise Snapshot

Reactive object that sync itself based on the latest snapshot of interaction with a Promise.

News

This stable version is compatible with Vue 2 using @vue/composition-api plugin.

If you want Vue 3 beta compatible version, then see here

Tips

If you want same functionality, but as component, then checkout vue-promise-builder.

Installation

  • Using NPM
npm install vue-promise-snapshot
  • Using Yarn
yarn add vue-promise-snapshot

Usage

You must install @vue/composition-api as a plugin via Vue.use() beforehand.

See @vue/composition-api.

<template>
  <section>
    <div v-if="generation.isStandby">
      <div>Generate number 1-1000</div>
      <button @click="generate()">Start</button>
    </div>
 
    <div v-if="generation.isPending">
      Generating...
    </div>
    <div v-else-if="generation.isFulfilled">
      {{ generation.result }}
    </div>
    <div v-else-if="generation.isRejected">
      {{ generation.error }}
    </div>
 
    <div v-if="generation.isSettled">
      <button @click="generate()">Retry</button>
    </div>
  </section>
</template>
 
<script>
import { usePromiseSnapshot } from 'vue-promise-snapshot'
 
export default {
  setup() {
    const generation = usePromiseSnapshot()
 
    async function generate() {
      generation.promise = _generate()
 
      try {
        await generation.promise
      } catch (error) {
        //
      }
    }
 
    // You can also use start method to get one-liner and type hints
 
    // async function generate() {
    //   try {
    //     await generation.start(_generate())
    //   } catch (error) {
    //     //
    //   }
    // }
 
    return {
      generation,
      generate,
    }
  },
}
 
async function _generate() {
  const random = (min, max) => Math.floor(Math.random() * Math.floor(max - min + 1)) + parseInt(min)
  await new Promise((resolve) => setTimeout(resolve, random(200, 2000)))
 
  if (random(0, 1)) {
    throw new Error('Failed to generate')
  }
 
  return random(1, 1000)
}
</script> 

API Reference

declare function usePromise<R>(): PromiseSnapshot<R>
 
interface PromiseSnapshot<R> {
  promise: Promise<R | any> | null
  readonly error: any
  readonly result: R | null | undefined
  readonly status: 'standby' | 'pending' | 'fulfilled' | 'rejected'
  readonly isStandby: boolean
  readonly isPending: boolean
  readonly isFulfilled: boolean
  readonly isRejected: boolean
  readonly isSettled: boolean
  readonly hasResult: boolean
  readonly hasError: boolean
  start<T>(promise: Promise<T>): Promise<T>
}

License

MIT

Package Sidebar

Install

npm i vue-promise-snapshot

Weekly Downloads

16

Version

1.1.3

License

MIT

Unpacked Size

9.79 kB

Total Files

7

Last publish

Collaborators

  • chabib