Skip to content

Redefine useAsync to separate config async config from parameters to the promiseFn #246

Description

@MrHus

This is a proposal for a change in the way useAsync works. I propose to add a third parameter, which is an object which is passed as the first argument to the promiseFn.

Currently this information is passed along in the AsyncOptions as [prop: string]: any:

export interface AsyncOptions<T> {
  promise?: Promise<T>
  promiseFn?: PromiseFn<T>
  // abbreviated
  debugLabel?: string
  [prop: string]: any
}

This makes the arguments to the promiseFn unsafe. Which is not nice for the developer experience. Plus it makes the AsyncOptions have a strange dual role.

My Proposal would create a dedicated parameter for the parameters to the promiseFn function like so :

type LoadDataConfig = {
  id: string
}

export function loadData(config: LoadDataConfig, props: AsyncProps<Link>, controller: AbortController) {
  return Link.one(config.id);
}

export default function AwesomeComponent() {
  const { id } = useParams();
  const state = useAsync(loadLink, { id }, { watch: id });
}

This would also mean redefining PromiseFn like so:

export type PromiseFn<T, C> = (config: C, props: AsyncProps<T>, controller: AbortController) => Promise<T>

Another less breaking options would be to add the config to AsyncOptions:

export interface AsyncOptions<T, C> {
  promise?: Promise<T>
  promiseFn?: PromiseFn<T>
  // abbreviated
  debugLabel?: string
config: C
  [prop: string]: any
}

This would at least make the config type safe, but makes the api a little nicer.

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions