Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@toplinker2/vue3-axios-request

Package Overview
Dependencies
Maintainers
2
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@toplinker2/vue3-axios-request

A wrapper for Axios with Vue3 componsition API, It's easy to use and support polling, retry, cache, debounce, throttle...

  • 1.0.4
  • latest
  • npm
  • Socket score

Version published
Weekly downloads
0
Maintainers
2
Weekly downloads
 
Created
Source

Vue3AxiosRequest

A wrapper for Axios with Vue3 componsition API, It's easy to use and support polling, retry, cache, debounce, throttle...

Features

  • Axios with Vue3 componsition API
  • Auto error retry
  • Reactive result with Vue3 ref
  • Interval polling
  • Debounce and throttle
  • Support any promise
  • Result caching support
  • Easy to use, simailar with axios.get(...) axios.post(...)
  • Written in Typescript, full type checking & code completion

Install

npm install @toplinker/vue3-axios-request
# or
yarn add @toplinker/vue3-axios-request

Usage

1. Quick Start
<template>
  <button @click.prevent="res.run()">Load Data</button>
  <div>
    <div>loading={{ res.loading }}</div>
    <div>error={{ res.error }}</div>
    <div>data={{ res.data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

/**
 * 1. import `useAxiosRequest`
 */
import { useAxiosRequest } from "@toplinker/vue3-axios-request";
export default defineComponent({
  setup() {
    /**
     * 2. create a http instance
     */
    const http = useAxiosRequest();

    /**
     * 3. use http.get(...) or http.post(..) similar as axios usage,
     *    only with an extra ExecuteOptions.
     */
    const res = http.get(
      "https://api.github.com/search/repositories", // URL
      { params: { q: "vue3-axios-request" } }, // AxiosRequestConfig
      { retryCount: 10, retryInterval: 100 } // ExecuteOptions
    );

    /**
     * 4. return a result, include data, error, loading, run(), ... Thoses values
     *    are Ref<>, so it can directly used in html template
     */
    return { res };
  },
});
</script>

2. Usage of useAxiosGet,useAxioPost ...

As a alternative, you can use useAxiosGet, useAxiosPost to realize the same function without create a useAxiosRequest instance.

<template>
  <button @click.prevent="res.run()">Load Data</button>
  <div>
    <div>loading={{ res.loading }}</div>
    <div>error={{ res.error }}</div>
    <div>data={{ res.data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

/**
 * 1. improt `useAxiosGet`,`useAxiosPost` etc.
 */
import { useAxiosGet } from "@toplinker/vue3-axios-request";
export default defineComponent({
  setup() {
    /**
     * 2. direct call function `useAxiosGet`.
     */
    const res = useAxiosGet(
      "https://api.github.com/search/repositories", // URL
      { params: { q: "vue3-axios-request" } }, // AxiosRequestConfig
      { retryCount: 10, retryInterval: 100 } // ExecuteOptions
    );

    /**
     * 3. return a result, include data, error, loading, run(), ... Thoses values
     *    are Ref<>, so it can directly used in html template
     */
    return { res };
  },
});
</script>

3. With Preset Settings

When create useAxiosRequest instance. you can preset some default AxiosRequestConfig and ExecuteOptions.

The full AxiosRequestConfig API, please see Axios Official Doc.

The full ExecuteOptions API, see below [API/ExecuteOptions] section.

<template>
  <button @click.prevent="res.run()">Load Data</button>
  <div>
    <div>loading={{ res.loading }}</div>
    <div>error={{ res.error }}</div>
    <div>data={{ res.data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

import { useAxiosRequest } from "@/toplinker/vue3-axios-request";
export default defineComponent({
  setup() {
    /**
     * 1. When create a AxiosRequest instance, preset some ExecuteOptions and AxiosRequestConfig
     */
    const http = useAxiosRequest(
      {
        debounceInterval: 300,
        loadingDelay: 200,
        retryCount: 10,
        retryInterval: 100,
        manual: true,
      },
      { baseURL: "https://api.github.com/" }
    );

    const res = http.get(
      "/search/repositories", // URL
      { params: { q: "vue3-axios-request" } } // AxiosRequestConfig
      // ExecuteOptions with preset setting
    );

    return { res };
  },
});
</script>

4. Multi Global Settings
useExecutionOptions

You can use useExecuteOptions('name') function to create a ExecuteOptions with a global name.

When execute useExecuteOptions('name'), if the name never used before, it will create a new one.

If the name alreay exists, it will return from global.

useAxios

Similar with useExecuteOptions('name'), useAxios('name') can create multiple global AxiosInstance

with different default request config, or different interceptors.

useExecuteOptions() and useAxios() without name, it will set the name as default

<template>
  <button @click.prevent="res.run('vue3-tony')">Load Data</button>
  <div>
    <div>loading={{ res.loading }}</div>
    <div>error={{ res.error }}</div>
    <div>data={{ res.data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useAxiosRequest, useExecuteOptions, useAxios } from "@toplinker/vue3-axios-request";
export default defineComponent({
  setup() {
    /**
     * 1. Create a new global ExecuteOptions with name `MyOptions`,
     *    and set it's default value
     */
    let myoptions = useExecuteOptions("MyOptions");
    myoptions.debounceInterval = 300;
    myoptions.retryCount = 10;
    myoptions.retryInterval = 100;
    myoptions.manual = true;
    // myoptions....

    /**
     * 2. Create a new global AxiosInstance with name `MyAxios`,
     *    then you can set the default AxiosRequestConfig and
     *    request or response interceptors
     */
    let myaxios = useAxios("MyAxios");
    myaxios.defaults.baseURL = "https://api.github.com/";
    // myaxios.interceptors.request.use(...)
    // myaxios.interceptors.response.use(...)

    /**
     * 3. Create AxiosRequest with global Axios and ExecuteOption by name.
     *    The name is case-insensitive
     */
    const http = useAxiosRequest("myoptions", "myaxios");
    const res = http.get(
      "/search/repositories", // URL
      { params: { q: "vue3-axios-request" } } // AxiosRequestConfig
      // ExecuteOptions with global setting
    );

    return { res };
  },
});

5. Run with parameters

As a alternative with static AxiosRequestConfig, you can also use a function with some parameters and return a AxiosRequestConfig.

After with functional AxiosRequestConfig, use run(...) can change the parameter to get different result.

<template>
  <button @click.prevent="res.run('vue2-axios')">Load Data</button>
  <div>
    <div>loading={{ res.loading }}</div>
    <div>error={{ res.error }}</div>
    <div>data={{ res.data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useAxiosRequest } from "@toplinker/vue3-axios-request";
export default defineComponent({
  setup() {
    /**
     * 1. Create a function return AxiosRequestConfig.
     *    it will use ExecutionOptions's `defaultParams` as arguments
     */
    const res = useAxiosRequest().get(
      "https://api.github.com/search/repositories",
      (search: string) => {
        return { params: { q: search } };
      }, // arrow function return a AxiosRequestConfig
      { defaultParams: ["vue3-axios-request"] } // ExecuteOptions with defaultParams
    );

    return { res };

    /**
     * 2. You can use `res.run(...)`, set new parameters to change the AxiosRequestConfig,
     *    then it will get different result data.
     *    (see in html template `@click.prevent="res.run('vue2-axios')`, [Line 2])
     */
  },
});
</script>

6. Run any Promise

We also provide useRequest to execute any Promise function. the useage is same as useAxiosRequest, just replace the AxiosRequestConfig with a Promise function.

Below example, we use fetch to replace axios. but any Promise function (even without network request) still works.

<template>
  <button @click.prevent="res.run('vue2-axios')">Load Data</button>
  <div>
    <div>loading={{ res.loading }}</div>
    <div>error={{ res.error }}</div>
    <div>data={{ res.data }}</div>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { useRequest } from "@/index.esm";

export default defineComponent({
  setup() {
    /**
     * 1. Create any funtion which return a Promise<R>
     */
    const query = (search: string) => {
      return fetch("https://api.github.com/search/repositories?q=" + search);
    };

    /**
     * 2. Execute `useRequest(...)` with default parameters
     */
    const res = useRequest(query, { defaultParams: ["vue3-axios-request"] });

    /**
     * 3. All `ExecuteOptions` and result features same as `useAxiosRequest`
     */
    return { res };

    /**
     * 4. Also can use `res.run(...)`, set new parameters to get different result data.
     *    (see in html template `@click.prevent="res.run('vue2-axios')`, [Line 2])
     */
  },
});
</script>

API

ExecuteOptions

OptionDataTypeDescription
initDataanyInitial result data
defaultParamsany[]Default parameters
pollingIntervalnumberPolling Interval (ms)
debounceIntervalnumberDebounce Interval (ms)
throttleIntervalnumberThrottle Interval (ms)
cacheKeystringCache key, use with cacheTime, next time if the cache is valid, will return cache value
cacheTimenumberCache expire time (seconds)
retryCountnumberMax error retry count
retryIntervalnumberEach error retry interval (ms)
loadingDelaynumberDelay to set loading (ms)
manualbooleanIf true will not auto execute, need manually call run() function
onBefore(params: P) => voidBefore execution callback
formatResult(data: R ) => anyData format callback, the return value will set to res.data
onSuccess(data:R, params: P) => voidSuccess callback
onError(error: AxiosError, params: P) => voidError callback
onAfter(data: R , error: AxiosError , params: P)After callback, nomatter success or error
defaultAxiosstring or AxiosRequestConfigDefault global axios name or a specific AxiosRequestConfig
defaultOptionsstring or ExecuteOptionsDefault global ExecuteOptions name or a specific settings

RequestResult

KeyDataTypeDescription
loadingRef<boolean>Loading flag
dataRef<R>Result data
errorRef<AxiosError>Error data
paramsRef<any[]>Last run parameters
run(...args: P) => Promise<void>Run request with new parameters
cancel() => voidCancel request
refresh() => void Run request wit last parameters
mutate(newdata: R) => voidChange result data

All Functions

FunctionDescription
useRequest(promise)Execute a Promise function
useAxiosRequest(options, axios)Create a request instance with preset options and axios
useAxiosRequest().get(url, params, options)A wapper for axios.get() with options
useAxiosRequest().post(url, params, options)A wapper for axios.post() with options
useAxiosRequest().delete(url, params, options)A wapper for axios.delete() with options
useAxiosRequest().put(url, params, options)A wapper for axios.put() with options
useAxiosRequest().patch(url, params, options)A wapper for axios.patch() with options
useAxiosRequest().head(url, params, options)A wapper for axios.head() with options
useAxiosRequest().request(params, options)A wapper for axios.request() with options
useAxiosGet(url, params, options)A quick usage of useAxiosRequest().get(url, params, options)
useAxiosPost(url, params, options)A quick usage of useAxiosRequest().post(url, params, options)
useAxiosDelete(url, params, options)A quick usage of useAxiosRequest().delete(url, params, options)
useAxiosPut(url, params, options)A quick usage of useAxiosRequest().put(url, params, options)
useAxiosPatch(url, params, options)A quick usage of useAxiosRequest().patch(url, params, options)
useAxiosHead(url, params, options)A quick usage of useAxiosRequest().head(url, params, options)
useAxios(name)Create or get a global AxiosInstance
useExecuteOptions(name)Create or get a global ExecuteOption
allAxiosInstance()Return all global AxiosInstance
allExecuteOptions()Return all global ExecuteOptions

Changelog

1.0.4

  • Fix README.

1.0.3

  • Fix TS compiler options, downgrade from ESNext to ES2015.

1.0.2

  • Fix dependencies in package.json

1.0.1

  • Change useOptions to useExecuteOptions, make it's meaning clearer.
  • Improve and fix README

1.0.0

  • First release

Keywords

FAQs

Package last updated on 18 Feb 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc