- Use catch to capture errors and store them at the component level in state
- Use the error state to render component level errors as feedback to the user
- Be careful what you catch and tell the user about
function User ({ username }) {
const [user, setUser] = React.useState({});
const [error, setError] = React.useState(null);
React.useEffect(() => {
fetchUser(username)
.then(setUser)
.catch(error => {
console.error(error);
setError(error);
});
}, [username])
if (error) {
return <p>{error.message}</p>
} else {
return <UserTable user={user} />
}
}