・This pattern shows alternative data instead of the data you exactly want to show when fetching data fails. This imporoves use experience better than showing nothing at all.
import { useState } from "react";
const FALLBACK_IMAGE_URL = "https://i.pravatar.cc/100?img=2";
function Avatar({ avatarUrl}) {
return <img src={avatarUrl ?? FALLBACK_IMAGE_URL} />;
}
function UserProfile({ user }) {
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
function App() {
const avatarUrl = "https://i.pravatar.cc/100?img=1";
const [user, setUser] = useState({
name: "John Doe",
email: "jsample@example.com",
avatarUrl,
});
const failTofetchAvater = () => {
setUser((prev) => ({ ...prev, avatarUrl: null }));
};
const restoreAvatar = () => {
setUser((prev) => ({
...prev,
avatarUrl,
}));
};
return (
<div>
<button onClick={failTofetchAvater}>Fail to fetch avater</button>
<button onClick={restoreAvatar}>Restore Avatar</button>
<UserProfile user={user} />
</div>
);
}
export default App;
Top comments (0)