mediumFrontend

How do you interact with external APIs in React?

552 views
01

Understand the problem

Discuss common patterns and tools for fetching data from and sending data to backend services in React applications.

apidata fetchinguseeffectaxios
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

A small typed API client
const BASE = "https://api.example.com"; // from import.meta.env in real apps

async function api(path, options = {}) {
  const res = await fetch(BASE + path, {
    headers: { "Content-Type": "application/json", ...options.headers },
    ...options,
  });
  if (!res.ok) throw new Error("HTTP " + res.status);
  return res.json();
}

import { useState } from "react";
export default function App() {
  const [user, setUser] = useState(null);
  const load = () => api("/users/1").then(setUser).catch(console.error);
  return (
    <div style={{ padding: 24, fontFamily: "system-ui" }}>
      <button onClick={load}>Load user</button>
      <pre>{user && JSON.stringify(user, null, 2)}</pre>
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

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