Research
Security News
Malicious PyPI Package ‘pycord-self’ Targets Discord Developers with Token Theft and Backdoor Exploit
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
@axios-use/vue
Advanced tools
A Vue composition utilities for Axios. Lightweight, cancelable and less change.
npm i axios @axios-use/vue
<script setup>
import { defineProps, toRef } from "vue";
import { useResource } from "@axios-use/vue";
const props = defineProps(["userId"]);
const userId = toRef(props, "userId");
const [reqState] = useResource((id) => ({ url: `/user/${id}` }), [userId]);
</script>
<template>
<div v-if="reqState.error">{{ reqState.error?.message || "error" }}</div>
<div v-else-if="reqState.isLoading === false">{{ reqState.data?.name }}</div>
<div v-else>...</div>
</template>
import { useRequest, useResource } from "@axios-use/vue";
config | type | default | explain |
---|---|---|---|
instance | object | axios | Axios instance. You can pass your axios with a custom config. |
getResponseItem | function | (r) => r.data | custom data value. The default value is response['data']. PR#1 |
import axios from "axios";
import AxiosUseVue from "@axios-use/vue";
import App from "./App.vue";
// custom Axios instance. https://github.com/axios/axios#creating-an-instance
const axiosInstance = axios.create({
baseURL: "https://example.com/",
});
const app = createApp(App);
// custom instance
app.use(AxiosUseVue, { instance: axiosInstance });
app.mount("#app");
// Vue.js v2.7
Vue.use(AxiosUseVue, { instance: axiosInstance });
option | type | explain |
---|---|---|
fn | function | get AxiosRequestConfig function |
options.onCompleted | function | This function is passed the query's result data. |
options.onError | function | This function is passed an RequestError object |
options.instance | AxiosInstance | Customize the Axios instance of the current item |
options.getResponseItem | function | custom returns the value of data (index 0). |
// js
const [createRequest, { hasPending, cancel }] = useRequest((id) => ({
url: `/user/${id}`,
method: "DELETE",
}));
// ts
const [createRequest, { hasPending, cancel }] = useRequest((id: string) =>
// response.data: Result. AxiosResponse<Result>
request<Result>({
url: `/user/${id}`,
method: "DELETE",
}),
);
interface CreateRequest {
// Promise function
ready: () => Promise<[Payload<T>, AxiosResponse]>;
// Axios Canceler. clear current request.
cancel: Canceler;
}
type HasPending = ComputedRef<boolean>;
// Axios Canceler. clear all pending requests(CancelTokenSource).
type Cancel = Canceler;
// options: onCompleted, onError
const [createRequest, { hasPending, cancel }] = useRequest(
(id) => ({
url: `/user/${id}`,
method: "DELETE",
}),
{
onCompleted: (data, response) => console.info(data, response),
onError: (err) => console.info(err),
},
);
option | type | explain |
---|---|---|
fn | function | get AxiosRequestConfig function |
parameters | array | false | fn function parameters. effect dependency list |
options.filter | function | Request filter. if return a falsy value, will not start the request |
options.defaultState | object | Initialize the state value. {data, response, error, isLoading} |
options.onCompleted | function | This function is passed the query's result data. |
options.onError | function | This function is passed an RequestError object |
options.instance | AxiosInstance | Customize the Axios instance of the current item |
options.getResponseItem | function | custom returns the value of data (index 0). |
// js
const [reqState, fetch, refresh, cancel] = useResource((id) => ({
url: `/user/${id}`,
method: "GET",
}));
// ts
const [reqState, fetch, refresh] = useResource((id: string) =>
// response.data: Result. AxiosResponse<Result>
request<Result>({
url: `/user/${id}`,
method: "GET",
}),
);
type ReqState = ComputedRef<{
// Result
data?: Payload<T>;
// axios response
response?: AxiosResponse;
// normalized error
error?: RequestError;
isLoading: boolean;
}>;
// `options.filter` will not be called
type Fetch = (...args: Parameters<T>) => Canceler;
// 1. Same as `fetch`. But no parameters required. Inherit `useResource` parameters
// 2. Will call `options.filter`
type Refresh = () => Canceler | undefined;
type Cancel = Canceler;
The request can also be triggered passing its arguments as dependencies to the useResource hook.
const userId = ref("001");
const [reqState] = useResource(
(id) => ({
url: `/user/${id}`,
method: "GET",
}),
[userId],
);
// no parameters
const [reqState] = useResource(
() => ({
url: "/users/",
method: "GET",
}),
[],
);
// conditional
const [reqState, request] = useResource(
(id) => ({
url: `/user/${id}`,
method: "GET",
}),
[userId],
{
filter: (id) => id !== "12345",
},
);
request("12345"); // custom request is still useful
// ComputedRef parameter
const params = computed(() => ({ id: unref(userId) }));
const [reqState, request] = useResource(
({ id }) => ({
url: `/user/${id}`,
method: "GET",
}),
[params],
);
// reactive parameter
const params = reactive({ id: userId });
const [reqState, request] = useResource(
({ id }) => ({
url: `/user/${id}`,
method: "GET",
}),
[params],
);
// options: onCompleted, onError
const [reqState] = useResource(
() => ({
url: "/users/",
method: "GET",
}),
[],
{
onCompleted: (data, response) => console.info(data, response),
onError: (err) => console.info(err),
},
);
The request
function allows you to define the response type coming from it. It also helps with creating a good pattern on defining your API calls and the expected results. It's just an identity function that accepts the request config and returns it. Both useRequest
and useResource
extract the expected and annotated type definition and resolve it on the response.data
field.
import { request } from "@axios-use/vue";
const api = {
getUsers: () => {
return request<Users>({
url: "/users",
method: "GET",
});
},
getUserInfo: (userId: string) => {
return request<UserInfo>({
url: `/users/${userId}`,
method: "GET",
});
},
};
You can also use these request
functions directly in axios
.
const usersRes = await axios(api.getUsers());
const userRes = await axios(api.getUserInfo("ID001"));
custom response type. (if you change the response's return value. like axios.interceptors.response
)
import { request, _request } from "@axios-use/vue";
const [reqState] = useResource(() => request<DataType>({ url: `/users` }));
// AxiosResponse<DataType>
unref(reqState).response;
// DataType
unref(reqState).data;
// custom response type
const [reqState] = useResource(() => _request<MyWrapper<DataType>>({ url: `/users` }));
// MyWrapper<DataType>
unref(reqState).response;
// MyWrapper<DataType>["data"]. maybe `undefined` type.
// You can use `getResponseItem` to customize the value of `data`
unref(reqState).data;
The createRequestError
normalizes the error response. This function is used internally as well. The isCancel
flag is returned, so you don't have to call axios.isCancel later on the promise catch block.
interface RequestError<T> {
data?: T;
message: string;
code?: string | number;
isCancel: boolean;
original: AxiosError<T>;
}
FAQs
A Vue composition utilities for Axios.
The npm package @axios-use/vue receives a total of 7 weekly downloads. As such, @axios-use/vue popularity was classified as not popular.
We found that @axios-use/vue demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
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.
Research
Security News
Socket researchers uncover the risks of a malicious Python package targeting Discord developers.
Security News
The UK is proposing a bold ban on ransomware payments by public entities to disrupt cybercrime, protect critical services, and lead global cybersecurity efforts.
Security News
Snyk's use of malicious npm packages for research raises ethical concerns, highlighting risks in public deployment, data exfiltration, and unauthorized testing.