cf.completefrontend

Predict the outputMedium

One tea in this menu has no price. What does the page log and show?

Price throws for a tea without a price. The boundary logs the caught error from componentDidCatch.

What does it log, and what does the page show?
import { Component } from "react";
 
class ErrorBoundary extends Component {
  state = { error: null };
 
  static getDerivedStateFromError(error) {
    return { error };
  }
 
  componentDidCatch(error) {
    console.log("caught", error.message);
  }
 
  render() {
    if (this.state.error) return <p>Sorry: {this.state.error.message}</p>;
    return this.props.children;
  }
}
 
function Price({ tea }) {
  console.log("Price", tea.name);
  if (tea.price === undefined) throw new Error(`No price for ${tea.name}.`);
  return <li>{tea.name}: ${tea.price}</li>;
}
 
export default function App() {
  return (
    <>
      <h1>Menu</h1>
      <ErrorBoundary>
        <ul>
          <Price tea={{ name: "Sencha", price: 4 }} />
          <Price tea={{ name: "Mystery" }} />
          <Price tea={{ name: "Assam", price: 3 }} />
        </ul>
      </ErrorBoundary>
      <p>Open until four.</p>
    </>
  );
}

It runs in development, rendered as <App />.

Practice it in the editor, with tests

The answer

Work out every line it logs, in order, and what the page shows at the end. Then check.

Checking your sign-in…