mediumFrontend

How do you handle asynchronous operations in React functional components?

930 views
01

Understand the problem

This question evaluates knowledge of managing side effects and data fetching in modern React.

asyncuseEffectdata fetchinghooks
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Async in a handler with pending + try/catch
import { useState } from "react";

export default function App() {
  const [pending, setPending] = useState(false);
  const [result, setResult] = useState("");

  async function save() {
    setPending(true);
    try {
      const res = await fetch("/api/save", { method: "POST" });
      setResult(res.ok ? "saved" : "failed");
    } catch (e) {
      setResult("error: " + e.message);
    } finally {
      setPending(false);
    }
  }

  return (
    <div style={{ padding: 24, fontFamily: "system-ui" }}>
      <button onClick={save} disabled={pending}>{pending ? "Saving…" : "Save"}</button>
      <p>{result}</p>
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.