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

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

Open
Tanimodori opened this issue Sep 29, 2022 · 5 comments

Comments

@Tanimodori
Copy link

Tanimodori commented Sep 29, 2022

需求描述 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
Copy link
Author

Tanimodori commented Sep 29, 2022

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
Copy link
Author

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

@Tanimodori Tanimodori reopened this Sep 29, 2022
@John60676
Copy link
Member

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

@Tanimodori
Copy link
Author

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

@yangmiao7
Copy link

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants