-
-
Notifications
You must be signed in to change notification settings - Fork 614
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
feat(utils): Add loadable #698
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,52 @@ | ||
import { atom } from 'jotai' | ||
import type { Atom } from 'jotai' | ||
|
||
const loadableAtomCache = new WeakMap<Atom<unknown>, Atom<Loadable<unknown>>>() | ||
const errorLoadableCache = new WeakMap<object, Loadable<never>>() | ||
|
||
type Loadable<Value> = | ||
| { state: 'loading' } | ||
| { state: 'hasError'; error: unknown } | ||
| { state: 'hasData'; data: Value } | ||
|
||
const LOADING_LOADABLE: Loadable<never> = { state: 'loading' } | ||
|
||
export function loadable<Value>(anAtom: Atom<Value>): Atom<Loadable<Value>> { | ||
const cachedAtom = loadableAtomCache.get(anAtom) | ||
if (cachedAtom) { | ||
return cachedAtom as Atom<Loadable<Value>> | ||
} | ||
|
||
const derivedAtom = atom((get): Loadable<Value> => { | ||
try { | ||
const value = get(anAtom) | ||
|
||
return { | ||
state: 'hasData', | ||
data: value, | ||
} | ||
} catch (error) { | ||
if (error instanceof Promise) { | ||
return LOADING_LOADABLE | ||
} | ||
|
||
const cachedErrorLoadable = errorLoadableCache.get(error as Error) | ||
|
||
if (cachedErrorLoadable) { | ||
return cachedErrorLoadable | ||
} | ||
|
||
const errorLoadable: Loadable<never> = { | ||
state: 'hasError', | ||
error, | ||
} | ||
|
||
errorLoadableCache.set(error as Error, errorLoadable) | ||
return errorLoadable | ||
} | ||
}) | ||
|
||
loadableAtomCache.set(anAtom, derivedAtom) | ||
|
||
return derivedAtom | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
import { fireEvent, render } from '@testing-library/react' | ||
import { Atom, atom } from '../../src/index' | ||
import { loadable, useAtomValue, useUpdateAtom } from '../../src/utils' | ||
import { getTestProvider } from '../testUtils' | ||
|
||
const Provider = getTestProvider() | ||
|
||
it('loadable turns suspense into values', async () => { | ||
let resolveAsync!: (x: number) => void | ||
const asyncAtom = atom(() => { | ||
return new Promise<number>((resolve) => (resolveAsync = resolve)) | ||
}) | ||
|
||
const { findByText, getByText } = render( | ||
<Provider> | ||
<LoadableComponent asyncAtom={asyncAtom} /> | ||
</Provider> | ||
) | ||
|
||
getByText('Loading...') | ||
resolveAsync(5) | ||
await findByText('Data: 5') | ||
}) | ||
|
||
it('loadable turns errors into values', async () => { | ||
let rejectAsync!: (error: Error) => void | ||
const asyncAtom = atom(() => { | ||
return new Promise<number>((resolve, reject) => (rejectAsync = reject)) | ||
}) | ||
|
||
const { findByText, getByText } = render( | ||
<Provider> | ||
<LoadableComponent asyncAtom={asyncAtom} /> | ||
</Provider> | ||
) | ||
|
||
getByText('Loading...') | ||
rejectAsync(new Error('An error occurred')) | ||
await findByText('Error: An error occurred') | ||
}) | ||
|
||
it('loadable turns primitive throws into values', async () => { | ||
let rejectAsync!: (errorMessage: string) => void | ||
const asyncAtom = atom(() => { | ||
return new Promise<number>((resolve, reject) => (rejectAsync = reject)) | ||
}) | ||
|
||
const { findByText, getByText } = render( | ||
<Provider> | ||
<LoadableComponent asyncAtom={asyncAtom} /> | ||
</Provider> | ||
) | ||
|
||
getByText('Loading...') | ||
rejectAsync('An error occurred') | ||
await findByText('Error: An error occurred') | ||
}) | ||
|
||
it('loadable goes back to loading after re-fetch', async () => { | ||
let resolveAsync!: (x: number) => void | ||
const refreshAtom = atom(0) | ||
const asyncAtom = atom((get) => { | ||
get(refreshAtom) | ||
return new Promise<number>((resolve) => (resolveAsync = resolve)) | ||
}) | ||
|
||
const Refresh = () => { | ||
const setRefresh = useUpdateAtom(refreshAtom) | ||
return ( | ||
<> | ||
<button onClick={() => setRefresh((value) => value + 1)}> | ||
refresh | ||
</button> | ||
</> | ||
) | ||
} | ||
|
||
const { findByText, getByText } = render( | ||
<Provider> | ||
<Refresh /> | ||
<LoadableComponent asyncAtom={asyncAtom} /> | ||
</Provider> | ||
) | ||
|
||
getByText('Loading...') | ||
resolveAsync(5) | ||
await findByText('Data: 5') | ||
fireEvent.click(getByText('refresh')) | ||
await findByText('Loading...') | ||
resolveAsync(6) | ||
await findByText('Data: 6') | ||
}) | ||
|
||
it('loadable can recover from error', async () => { | ||
let resolveAsync!: (x: number) => void | ||
let rejectAsync!: (error: Error) => void | ||
const refreshAtom = atom(0) | ||
const asyncAtom = atom((get) => { | ||
get(refreshAtom) | ||
return new Promise<number>((resolve, reject) => { | ||
resolveAsync = resolve | ||
rejectAsync = reject | ||
}) | ||
}) | ||
|
||
const Refresh = () => { | ||
const setRefresh = useUpdateAtom(refreshAtom) | ||
return ( | ||
<> | ||
<button onClick={() => setRefresh((value) => value + 1)}> | ||
refresh | ||
</button> | ||
</> | ||
) | ||
} | ||
|
||
const { findByText, getByText } = render( | ||
<Provider> | ||
<Refresh /> | ||
<LoadableComponent asyncAtom={asyncAtom} /> | ||
</Provider> | ||
) | ||
|
||
getByText('Loading...') | ||
rejectAsync(new Error('An error occurred')) | ||
await findByText('Error: An error occurred') | ||
fireEvent.click(getByText('refresh')) | ||
await findByText('Loading...') | ||
resolveAsync(6) | ||
await findByText('Data: 6') | ||
}) | ||
|
||
interface LoadableComponentProps { | ||
asyncAtom: Atom<number | string> | ||
} | ||
|
||
const LoadableComponent = ({ asyncAtom }: LoadableComponentProps) => { | ||
const value = useAtomValue(loadable(asyncAtom)) | ||
|
||
if (value.state === 'loading') { | ||
return <>Loading...</> | ||
} | ||
|
||
if (value.state === 'hasError') { | ||
return <>{String(value.error)}</> | ||
} | ||
|
||
return <>Data: {value.data}</> | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As we're using a
WeakMap
, I added this test case. If a primitive value ever became a key forerror
, it wouldn't work.