All Projects → VitorLuizC → Vue Loadable

VitorLuizC / Vue Loadable

Licence: mit
⏳ Improve your loading state control with pretty simple methods and helpers.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to Vue Loadable

Rubico
[a]synchronous functional programming
Stars: ✭ 133 (+478.26%)
Mutual labels:  async, asynchronous, promise
Before After Hook
wrap methods with before/after hooks
Stars: ✭ 49 (+113.04%)
Mutual labels:  async, asynchronous, promise
Metasync
Asynchronous Programming Library for JavaScript & Node.js
Stars: ✭ 164 (+613.04%)
Mutual labels:  async, asynchronous, promise
Kitchen Async
A Promise library for ClojureScript, or a poor man's core.async
Stars: ✭ 128 (+456.52%)
Mutual labels:  async, asynchronous, promise
Sieppari
Small, fast, and complete interceptor library for Clojure/Script
Stars: ✭ 133 (+478.26%)
Mutual labels:  async, promise, interceptor
Tascalate Concurrent
Implementation of blocking (IO-Bound) cancellable java.util.concurrent.CompletionStage and related extensions to java.util.concurrent.ExecutorService-s
Stars: ✭ 144 (+526.09%)
Mutual labels:  async, asynchronous, promise
Creed
Sophisticated and functionally-minded async with advanced features: coroutines, promises, ES2015 iterables, fantasy-land
Stars: ✭ 265 (+1052.17%)
Mutual labels:  async, asynchronous, promise
Axios Auth Refresh
Library that helps you implement automatic refresh of authorization via axios interceptors. You can easily intercept the original request when it fails, refresh the authorization and continue with the original request, without user even noticing.
Stars: ✭ 502 (+2082.61%)
Mutual labels:  promise, interceptor
Kneden
Transpile ES2017 async/await to vanilla ES6 Promise chains: a Babel plugin
Stars: ✭ 517 (+2147.83%)
Mutual labels:  async, promise
Then
🎬 Tame async code with battle-tested promises
Stars: ✭ 908 (+3847.83%)
Mutual labels:  async, promise
Tornado Celery
Non-blocking Celery client for Tornado
Stars: ✭ 561 (+2339.13%)
Mutual labels:  async, asynchronous
Blockly Gamepad
A Blockly extension designed to develop games (made with love ❤)
Stars: ✭ 18 (-21.74%)
Mutual labels:  async, asynchronous
Asyncro
⛵️ Beautiful Array utilities for ESnext async/await ~
Stars: ✭ 487 (+2017.39%)
Mutual labels:  asynchronous, promise
Thunks
A small and magical composer for all JavaScript asynchronous.
Stars: ✭ 523 (+2173.91%)
Mutual labels:  asynchronous, promise
React Hooks Async
React custom hooks for async functions with abortability and composability
Stars: ✭ 459 (+1895.65%)
Mutual labels:  async, promise
Posterus
Composable async primitives with cancelation, control over scheduling, and coroutines. Superior replacement for JS Promises.
Stars: ✭ 536 (+2230.43%)
Mutual labels:  async, promise
Godot Gametemplate
Template with all necessary stuff taken care, just create your games main features.
Stars: ✭ 435 (+1791.3%)
Mutual labels:  async, loading
Zsh Async
Because your terminal should be able to perform tasks asynchronously without external tools!
Stars: ✭ 528 (+2195.65%)
Mutual labels:  async, asynchronous
P Map
Map over promises concurrently
Stars: ✭ 639 (+2678.26%)
Mutual labels:  async, promise
Swiftcoroutine
Swift coroutines for iOS, macOS and Linux.
Stars: ✭ 690 (+2900%)
Mutual labels:  async, asynchronous

vue-loadable

Build Status License Library minified size Library minified + gzipped size FOSSA Status

vue-loadable improves your loading state flow by providing methods and helpers to manage it.

<template>
  <p v-if="$isLoading('initialize')">Initializing...</p>
  <div v-else>
    <!-- Loaded content... -->
  </div>
</template>

<script>
import { mapActions } from 'vuex';
import { loadable, mapLoadableMethods } from 'vue-loadable';

export default {
  ...,

  methods: {
    async initialize () {
      // Set initialize state as loading on async function start.
      this.$setLoading('initialize');

      try {
        await this.$store.dispatch('users/fetchUsers');
      } catch (_) {}

      // Unset initialize state as loading on async function end.
      this.$unsetLoading('initialize');
    },

    // `loadable` decorator can automate this process.
    initialize: loadable(async function () {
      await this.$store.dispatch('users/fetchUsers');
    }, 'initialize'),

    // An there's `mapLoadableMethods` to map methods into loadable methods (works with Vuex too).
    ...mapLoadableMethods(
      mapActions('users', {
        initialize: 'fetchUsers'
      })
    )
  },
  mounted () {
    this.initialize();
  }
};

Installation

This library is published in the NPM registry and can be installed using any compatible package manager.

npm install --save vue-loadable

# Use the command below if you're using Yarn.
yarn add vue-loadable

Installation from CDN

This module has an UMD bundle available through JSDelivr and Unpkg CDNs.

<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-loadable"></script>

<script>
  // module will be available through `VueLoadable` object.
  console.log(VueLoadable);

  Vue.use(VueLoadable);
</script>

Installation on Vue

vue-loadable need to be installed to enable loadable methods, loadable decorator and mapLoadableMethods helper.

To install globally, just pass default exported object as argment to Vue.use.

import Vue from 'vue';
import Loadable from 'vue-loadable';

Vue.use(Loadable);

You can install it locally instead with LoadableMixin mixin.

<script>
import { LoadableMixin } from 'vue-loadable';

export default {
  mixins: [LoadableMixin],
};
</script>

API

  • loadable decorates a function to change loading state during its execution. It sets the state as loading when function inits and unsets when it throws an error, when it resolves or when it returns a value.

    Second argument is the loading state name, is "unknown" when it's not defined.

    Vue.component('SignInForm', {
      methods: {
        signIn: loadable(async function(name) {
          // ...
        }, 'signIn'),
      },
    
      async mounted() {
        this.$isLoading('signIn');
        //=> false
    
        const promise = this.signIn('Vitor');
    
        this.$isLoading('signIn');
        //=> true
    
        await promise;
    
        this.$isLoading('signIn');
        //=> false
      },
    });
    

    It passes down the function arguments, rejects the errors and resolves the returned value.

    async function confirmUsername(username: string): Promise<boolean> {
      // ...
    }
    
    export default {
      methods: {
        // Returns a function with same signature, but handling loading states.
        confirm: loadable(confirmUsername, 'confirmation'),
      },
      async mounted(): Promise<void> {
        try {
          const isConfirmed = await this.confirm('VitorLuizC');
          this.$router.push(isConfirmed ? '/checkout' : '/confirmation');
        } catch (error) {
          new Rollbar.Error(error).send();
        }
      },
    };
    
    TypeScript type definitions.
    type Method =
      | ((...args: any[]) => any)
      | ((this: Vue, ...args: any[]) => any);
    
    type LoadableMethod<T extends Method> = (
      this: Vue,
      ...args: Parameters<T>
    ) => ReturnType<T> extends Promise<any>
      ? ReturnType<T>
      : Promise<ReturnType<T>>;
    
    const loadable: <T extends Method>(
      method: T,
      state?: string,
    ) => LoadableMethod<T>;
    
  • mapLoadableMethods maps methods into loadable ones that triggers loading states, it works pretty well with Vuex.

    It uses method's names as loading state name.

    <template>
      <div v-if="$isLoading('signInUser')">
        Carregando...
      </div>
      <div v-else>
        <SignedUserArea />
      </div>
    </template>
    
    <script>
    import { mapActions } from 'vuex';
    import { mapLoadableMethods } from 'vue-loadable';
    
    export default {
      methods: mapLoadableMethods(
        mapActions([
          'signInUser',
          'signUpUser'
        ])
      )
    };
    
    TypeScript type definitions.
    // `Method` and `LoadableMethod` are defined at `loadable` type definitions.
    
    type Methods = Record<string, Method>;
    
    type LoadableMethods<T extends Methods> = {
      [K in keyof T]: LoadableMethod<T[K]>;
    };
    
    const mapLoadableMethods: <T extends Methods>>(
      methods: T,
    ) => LoadableMethods<T>;
    
  • $isLoading is a method to check if a state is loading.

    Argument is the loading state name, is "unknown" when it's not defined.

    <template>
      <v-spinner v-if="$isLoading('initialize')" />
      <sign-in-form v-else @click="onClickSignIn" ... />
    </template>
    
    <script>
    // ...
    
    export default {
      methods: {
        ...,
        onClickSignIn () {
          if (!this.$isLoading('signIn')) // Call `signIn` only if its not loading.
            return;
    
          this.signIn();
        }
      }
    };
    
    TypeScript type definitions.
    interface Vue {
      $isLoading(state?: string): boolean;
    }
    
  • $isLoadingAny is a method to check if any state is loading.

    <template>
      <v-spinner v-if="$isLoadingAny()" />
      <div>
        <sign-in-or-sign-up-form @signIn="onSignIn" @signUp="onSignUp" />
      </div>
    </template>
    
    <script>
    // ...
    
    export default {
      methods: {
        ...,
        onSignUp () {
          if (!this.$isLoadingAny())
            return;
    
          this.signUp();
        },
        onSignIn () {
          if (!this.$isLoadingAny())
            return;
    
          this.signIn();
        }
      }
    };
    
    TypeScript type definitions.
    interface Vue {
      $isLoadingAny(): boolean;
    }
    
  • $setLoading is a method to set state as loading.

    Argument is the loading state name, is "unknown" when it's not defined.

    export default {
      methods: {
        ...,
        async onSubmit () {
          this.$setLoading('submission'); // set submission state as loading.
    
          await services.submit(this.fields);
        }
      }
    };
    
    TypeScript type definitions.
    interface Vue {
      $setLoading(state?: string): void;
    }
    
  • $unsetLoading is a method to unset state as loading.

    Argument is the loading state name, is "unknown" when it's not defined.

    export default {
      methods: {
        ...,
        async onSubmit () {
          try {
            await services.submit(this.fields);
          } catch {}
    
          this.$unsetLoading('submission'); // unset submission state as loading.
        }
      }
    };
    
    TypeScript type definitions.
    interface Vue {
      $unsetLoading(state?: string): void;
    }
    

License

Released under MIT License.

FOSSA Status

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].