首页 > 其他分享 >[React] Error boundary

[React] Error boundary

时间:2022-10-11 01:55:26浏览次数:44  
标签:setUserId const undefined userId value React User 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>
    )
}

 

标签:setUserId,const,undefined,userId,value,React,User,Error,boundary
From: https://www.cnblogs.com/Answer1215/p/16777945.html

相关文章