Data loaded over a network has several states. Render each one properly.
What to build
A Result component that shows the loading, error, empty and success states.
Requirements
- Write
Result({ state })wherestateis{ status: "loading" },{ status: "error", message }or{ status: "success", items }. Each version is wrapped in adivwith the classresult. - Loading: a
pLoading…. Error: apwith the classerrorshowingError: MESSAGEand abuttonTry again. Success with no items: apNothing found. Success with items: aulwith anliper item (the items are strings; use them as keys). Apprenders four results: loading; an error with the messageNetwork down; success with no items; success withTea,Milk.
Constraints
One component handles all four states.
Example
The four boxes show "Loading…", "Error: Network down" with a Try again button, "Nothing found", and a list of Tea and Milk.
Why it works
Returning early for loading and error leaves only the success case at the end, where a conditional operator decides between the empty message and the list.
Hints
Hint 1
Check state.status first and return early for loading and error.
Hint 2
For success, choose between "Nothing found" and the list with the conditional operator.
Solution
Show one correct solution (try it yourself first)
function Result({ state }) {
if (state.status === "loading") {
return (
<div className="result">
<p>Loading…</p>
</div>
);
}
if (state.status === "error") {
return (
<div className="result">
<p className="error">Error: {state.message}</p>
<button>Try again</button>
</div>
);
}
return (
<div className="result">
{state.items.length === 0 ? (
<p>Nothing found</p>
) : (
<ul>
{state.items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
)}
</div>
);
}
export default function App() {
return (
<div>
<Result state={{ status: "loading" }} />
<Result state={{ status: "error", message: "Network down" }} />
<Result state={{ status: "success", items: [] }} />
<Result state={{ status: "success", items: ["Tea", "Milk"] }} />
</div>
);
}