React: Every state of a request

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 }) where state is { status: "loading" }, { status: "error", message } or { status: "success", items }. Each version is wrapped in a div with the class result.
  • Loading: a p Loading…. Error: a p with the class error showing Error: MESSAGE and a button Try again. Success with no items: a p Nothing found. Success with items: a ul with an li per item (the items are strings; use them as keys).
  • App renders four results: loading; an error with the message Network down; success with no items; success with Tea, 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>
  );
}

Lesson: Conditional rendering →