Skip to content

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

License

Notifications You must be signed in to change notification settings

VitorLuizC/vue-loadable

Repository files navigation

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