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

Improve specificity of return type #49

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 17 additions & 11 deletions src/usePromise.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
import { useEffect, useState, useRef } from 'react'

type PromiseState<T> = {
loading: true
error: null
value: undefined
} | {
loading: false
error: null
value: T
} | {
loading: false
error: Error
value: undefined
};

export default function usePromise<T>(
promiseOrFn: (() => Promise<T>) | Promise<T>
): {
loading: boolean
error: Error | null
value: T | undefined
} {
const [state, setState] = useState<{
loading: boolean
error: Error | null
value: T | undefined
}>({
): PromiseState<T> {
const [state, setState] = useState<PromiseState<T>>({
loading: !!promiseOrFn,
error: null,
value: undefined
Expand All @@ -22,7 +28,7 @@ export default function usePromise<T>(
if (!promiseOrFn) {
setState({
loading: false,
error: null,
error: new TypeError(`The argument passed to usePromise must be either a promise or a function, but you passed a ${typeof promiseOrFn}`),
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Alternatively, this could throw a type error instead b/c a falsy value in promiseOrFn doesn't satisfy the type specified for the hook argument. Throwing an error might be better than setting an error on the state since this has the potential to be incorrectly interpreted as a rejected promise. 🤷 Would like your input on this please.

value: undefined
})
} else {
Expand Down