[React] Error boundary

import {ErrorBoundary, FallbackProps} from 'react-error-boundary'

const userState = selectorFamily({
    key: 'user',
    get: (userId: number) => async () => {
        const userData = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`).then((res) => res.json())
        if (userId === 4) {
            throw new Error('User does not exists')
        }
        return userData
    },
})

const ErrorFallback = ({error, resetErrorBoundary}: FallbackProps) => {
    return (
        <div>
            <Heading as="h2" size="md" mb={1}>
                Something went wrong
            </Heading>
            <Text>{error.message}</Text>
            <Button onClick={resetErrorBoundary}>OK</Button>
        </div>
    )
}

export const Async = () => {
    const [userId, setUserId] = useState<number | undefined>(undefined)

    return (
        <Container py={10}>
            <Heading as="h1" mb={4}>
                View Profile
            </Heading>
            <Heading as="h2" size="md" mb={1}>
                Choose a user:
            </Heading>
            <Select
                placeholder="Choose a user"
                mb={4}
                value={userId}
                onChange={(event) => {
                    const value = event.target.value
                    setUserId(value ? parseInt(value) : undefined)
                }}
            >
                <option value="1">User 1</option>
                <option value="2">User 2</option>
                <option value="3">User 3</option>
                <option value="4">User 4</option>
            </Select>
            {userId !== undefined && (
                <ErrorBoundary
                    FallbackComponent={ErrorFallback}
                    onReset={() => setUserId(undefined)}
                    resetKeys={[userId]} /* reset whenever userId changed */
                >
                    <Suspense fallback={<div>loading...</div>}>
                        <UserData userId={userId} />
                    </Suspense>
                </ErrorBoundary>
            )}
        </Container>
    )
}

 

posted @ 2022-10-11 01:48  Zhentiw  阅读(55)  评论(0编辑  收藏  举报