|
| 1 | +import { Suspense } from 'react' |
| 2 | +import { atom, useAtom, useSetAtom } from 'jotai' |
| 3 | +import { atomWithSuspenseQuery } from 'jotai-tanstack-query' |
| 4 | +import { ErrorBoundary, type FallbackProps } from 'react-error-boundary' |
| 5 | + |
| 6 | +const idAtom = atom(1) |
| 7 | +const userAtom = atomWithSuspenseQuery<User>((get) => ({ |
| 8 | + queryKey: ['user', get(idAtom)], |
| 9 | + queryFn: async ({ queryKey: [, id] }) => { |
| 10 | + const randomNumber = Math.floor(Math.random() * 10) |
| 11 | + if (randomNumber % 3 === 0) { |
| 12 | + await fetch(`https://jsonplaceholder.typicode.com/users/error`) |
| 13 | + return await Promise.reject('fetch failed') |
| 14 | + } |
| 15 | + |
| 16 | + const res = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`) |
| 17 | + return res.json() |
| 18 | + }, |
| 19 | + retry: false, |
| 20 | +})) |
| 21 | + |
| 22 | +const UserData = () => { |
| 23 | + const [{ data }] = useAtom(userAtom) |
| 24 | + |
| 25 | + return ( |
| 26 | + <> |
| 27 | + <UserDisplay user={data} /> |
| 28 | + </> |
| 29 | + ) |
| 30 | +} |
| 31 | + |
| 32 | +interface User { |
| 33 | + id: number |
| 34 | + name: string |
| 35 | + email: string |
| 36 | +} |
| 37 | + |
| 38 | +const UserDisplay = ({ user }: { user: User }) => { |
| 39 | + return ( |
| 40 | + <div> |
| 41 | + <div>ID: {user.id}</div> |
| 42 | + <strong>{user.name}</strong> - {user.email} |
| 43 | + </div> |
| 44 | + ) |
| 45 | +} |
| 46 | + |
| 47 | +const Controls = () => { |
| 48 | + const [id, setId] = useAtom(idAtom) |
| 49 | + return ( |
| 50 | + <> |
| 51 | + <div> |
| 52 | + ID: {id}{' '} |
| 53 | + <button type="button" onClick={() => setId((c) => c - 1)}> |
| 54 | + Prev |
| 55 | + </button>{' '} |
| 56 | + <button type="button" onClick={() => setId((c) => c + 1)}> |
| 57 | + Next |
| 58 | + </button> |
| 59 | + </div> |
| 60 | + </> |
| 61 | + ) |
| 62 | +} |
| 63 | + |
| 64 | +const Fallback = ({ error, resetErrorBoundary }: FallbackProps) => { |
| 65 | + const reset = useSetAtom(userAtom) |
| 66 | + const retry = () => { |
| 67 | + reset() |
| 68 | + resetErrorBoundary() |
| 69 | + } |
| 70 | + return ( |
| 71 | + <div role="alert"> |
| 72 | + <p>Something went wrong:</p> |
| 73 | + <pre>{error.message}</pre> |
| 74 | + <button onClick={retry}>Try again</button> |
| 75 | + </div> |
| 76 | + ) |
| 77 | +} |
| 78 | + |
| 79 | +const App = () => { |
| 80 | + return ( |
| 81 | + <ErrorBoundary FallbackComponent={Fallback}> |
| 82 | + <Suspense fallback="Loading..."> |
| 83 | + <Controls /> |
| 84 | + <UserData /> |
| 85 | + </Suspense> |
| 86 | + </ErrorBoundary> |
| 87 | + ) |
| 88 | +} |
| 89 | + |
| 90 | +export default App |
0 commit comments