Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feat: getResponseItem options (custom data value) #1

Merged
merged 9 commits into from
May 20, 2023

Conversation

wangcch
Copy link
Contributor

@wangcch wangcch commented May 10, 2023

use getResponseItem function to custom returns the value of data.

export _request function to custom data or response type. The request function is base on _request.

// source code
export const request = <T, D = any>(config: AxiosRequestConfig<D>) =>
  _request<AxiosResponse<T, D>, D>(config);

custom data

type ComResponse<T> = {
  code: number;
  result?: T;
  msg: string;
};
const [res] = useResource(() => ({ method: "get", url: "/users" }), [], {
  getResponseItem: (r) => r.data.result,
});

unref(res).data; // ComResponse<T>['result'] | undefined
unref(res).response; // AxiosResponse<ComResponse<T>>

For typescript we also need custom the request type

// not `request`
import { _request, useResource } from "@axios-use/vue";

const [res] = useResource(
  () => _request<AxiosResponse<ComResponse<UserListType>>, any, "data", "result">({ method: "get", url: "/users" }),
  [],
  {
    getResponseItem: (r) => r.data.result,
  },
);

unref(res).data; // ComResponse<T>['result'] | undefined
unref(res).response; // AxiosResponse<ComResponse<T>>
- () => request<ComResponse<UserListType>>({ /** ... */ }),
+ () => _request<AxiosResponse<ComResponse<UserListType>>, any, "data", "result">({ /** ... */ }),

custom response

For example, custom response in Axios interceptors.

axios.interceptors.response.use((d) => d.data);
unref(res).data; // ComResponse<T>['data']. It's always undefined
unref(res).response; // ComResponse<T> | undefined

For data we need custom data return. and custom request type.

import { _request, useResource } from "@axios-use/vue";

const myrequest = <T> = (config: AxiosRequestConfig) => _request<ComResponse<T>, any, 'result'>(config)

const [res] = useResource(
  () => myrequest<UserListType>({ method: "get", url: "/users" }),
  [],
  {
    getResponseItem: (r: ComResponse<UserListType>) => r.result,
  },
);

unref(res).data; // UserListType | undefined
unref(res).response; // ComResponse<UserListType> | undefined

@wangcch wangcch marked this pull request as ready for review May 19, 2023 03:18
@wangcch wangcch merged commit c6dcc33 into dev May 20, 2023
3 checks passed
@wangcch wangcch deleted the feat-options-getResponseItem branch May 20, 2023 15:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

1 participant