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

better Result inference in useAsync hook #1568

Open
Onxi95 opened this issue Dec 3, 2024 · 0 comments
Open

better Result inference in useAsync hook #1568

Onxi95 opened this issue Dec 3, 2024 · 0 comments

Comments

@Onxi95
Copy link

Onxi95 commented Dec 3, 2024

Hello 👋 Thank you for the awesome library!

New Features

  • better Result inference in useAsync hook

What is the new or updated feature that you are suggesting?

I think the return type of useAsync hook might be improved. Currently, status doesn't narrow the Result type:

async function Example() {
	const [{ status, result }, { execute }] = useAsync(promise);
	if (status === 'error') {
		return ...;
	}
	if (status === 'loading' || status === 'not-executed') {
		return ...;
	}
	if (status === 'success') {
		const test = result.body; // result is possibly `undefined`
	}
}

so we have to additionally check if the result exists, even if the status is success.
I guess it is a result of Result | undefined union in a second overload: https://github.com/react-hookz/web/blob/master/src/useAsync/index.ts#L57

it would be great if an exhaustive status check was enough to narrow the return type like:

async function Example() {
	const [{ status, result }, { execute }] = useAsync(promise);
	if (status === 'error') {
		return ...;
	}
	if (status === 'loading' || status === 'not-executed') {
		return ...;
	}
	const test = result.body; // correctly inferred as `Result`, without `undefined`
}

I was inspired by the behavior of React Query and their overloads: https://github.com/TanStack/query/blob/main/packages/react-query/src/useQuery.ts and prepared a simple demo in order to achieve the desired result: master...Onxi95:react-hookz:poc/async-state-discriminated-union

I didn't go very far with this, so I would have to read carefully if the types are consistent with the hook's runtime behavior.

Why should this feature be included?

It will improve a developer experience, as well as the readability.
Let me know what do you think about it - if it looks good - are you open for a PR? 😄

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

No branches or pull requests

1 participant