vue-request icon indicating copy to clipboard operation
vue-request copied to clipboard

[Feature Request] Types: Remove nullish check if initialData is given in useRequest

Open Tanimodori opened this issue 3 years ago • 5 comments

需求描述 Feature Description

If initialData is given, the result type should not have the undefined part.

The ref function in vue is a good example:

export declare function ref<T>(value: T): Ref<UnwrapRef<T>>;

export declare function ref<T = any>(): Ref<T | undefined>;

建议的解决方案 Proposed Solution

  1. Remove the | undefined part in State
export type State<R, P> = {
    loading: Ref<boolean>;
    data: Ref<R>; // <- Remove undefined
    error: Ref<Error | undefined>;
    params: Ref<P>;
};
  1. Add a type param for Option
// Add typeParam D
export type Options<R, P extends unknown[], D = undefined> = BaseOptions & {
  defaultParams?: P;
  ready?: Ref<boolean>;
  initialData?: D; // Changed to D
  refreshDeps?: WatchSource<any>[];
  cacheKey?: string | ((params?: P) => string);
  refreshDepsAction?: () => void;
  onSuccess?: (data: R, params: P) => void;
  onError?: (error: Error, params: P) => void;
  onBefore?: (params: P) => void;
  onAfter?: (params: P) => void;
};
  1. Modify the QueryState interface and useRequest signature.
// Add typeParam D
export interface QueryState<R, P extends unknown[], D = undefined> extends State<R | D, P> {
  run: (...arg: P) => Promise<R | null>;
  cancel: () => void;
  refresh: () => Promise<R | null>;
  mutate: Mutate<R>;
}

// Add typeParam D
function useRequest<R, P extends unknown[] = any, D = undefined>(
  service: Service<R, P>,
  options?: Options<R, P, D>, // Add D
): QueryResult<R, P, D>;     // Add D

Same modification is needed for useLoadMore, usePagination.

其他信息 Other information

Tanimodori avatar Sep 29 '22 03:09 Tanimodori

I found that the data is set to undefined when the request fails instead of retaining last results. If this is the expected behaviour never mind what I said.

Tanimodori avatar Sep 29 '22 03:09 Tanimodori

#82 如果出错也不会重置的话,还是加上去比较好。

Tanimodori avatar Sep 29 '22 08:09 Tanimodori

这个问题有待讨论,泛型这个方案不太好

John60676 avatar Sep 29 '22 10:09 John60676

如果不在乎“不传默认值时Service<R>可以返回undefined”的话,是可以省掉D的,根据useRequest的调用签名判断传没传默认值,然后决定R到底加不加undefined就行。

Tanimodori avatar Sep 29 '22 13:09 Tanimodori

这个问题有迭代的计划吗?

yangmiao7 avatar Mar 31 '23 07:03 yangmiao7