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

Request: useAsyncStatus - convert an async function into pending/loading/success/error states + a trigger. #309

Open
dwjohnston opened this issue Jun 6, 2024 · 0 comments

Comments

@dwjohnston
Copy link

dwjohnston commented Jun 6, 2024

The idea is instead of writing a component like:

export function MyComponent(props: {
  doSomethingAsync: () => Promise<'a' | 'b' | 'c'>;
}) {
  const [status, setStatus] = useState<PossibleStates<'a' | 'b' | 'c'>>({
    state: 'pending',
  });

  return (
    <div>
      {status.state === 'loading' && 'Loading...'}
      {status.state === 'error' && 'Error!'}
      <button
        onClick={async () => {
          setStatus({ state: 'loading' });
          try {
            const result = await props.doSomethingAsync();
            setStatus({ state: 'success', data: result });
          } catch (err) {
            setStatus({ state: 'error' });
          }
        }}
      >
        Click me
      </button>
    </div>
  );
}

We would do this:

export function MyComponent(props: {
  doSomethingAsync: () => Promise<'a' | 'b' | 'c'>;
}) {
  const [trigger, status] = useAsyncStatus(props.doSomethingAsync);

  return (
    <div>
      {status.state === 'loading' && 'Loading...'}
      {status.state === 'error' && 'Error!'}
      <button onClick={trigger}>Click me</button>
    </div>
  );
}

Some considerations

  1. Some users would rather use async functions that return errors rather than throw errors.
    eg.
type AsyncFunction<TArgs extends Array<unknown>, TData, TError> = 
    (...args: TArgs) => Promise<{data: TData} | {error: TError}>  
  1. Further gold plating could allow for the hook to also provide for the various feedback rendering, eg:
export function MyComponent(props: {
  doSomethingAsync: () => Promise<'a' | 'b' | 'c'>;
}) {
  const [trigger, status, feedbackJsx] = useAsyncStatus(props.doSomethingAsync, {
      loadingJsx: <span>Loading...</span> 
      errorJsx: <span>Error!</span>
  });

  return (
    <div>
      {feedbackJsx}
      <button onClick={trigger}>Click me</button>
    </div>
  );
}
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

No branches or pull requests

1 participant