So far tasks live in the browser. Real apps keep data on a server, so it's on every device and safe if the browser is cleared. In this lesson our React To-Do app talks to the To-Do API you build in the Node.js Backend course: sign up, log in, and tasks stored in PostgreSQL.
Before you start: run the backend
You need the API from the Node.js course running on your computer (it listens on port 3000). If you haven't built it yet, follow that course up to the CRUD lesson. Then, in its folder:
# in the tasks-api folder (the backend)$bun run dev
Keep it running, and in a second terminal start the React app as usual with bun run dev.
How the pieces fit
- 1
π
LoginForm
Sends email and password to /api/auth/login and gets back a token.
- 2
ποΈ
App
Saves the token. Token? Show TasksPage. No token? Show LoginForm.
- 3
πͺ
useTasks hook
Loads tasks when the page opens and has add, toggle and delete functions.
- 4
π‘
api/client.ts
Every request: adds the token, sends JSON, turns API errors into messages.
- 5
ποΈ
Express API + PostgreSQL
Checks the token and reads or saves the tasks.
The new files
src/ βββ api/ β βββ client.ts β NEW: all requests to the backend βββ hooks/ β βββ useTasks.ts β NEW: load + add / toggle / delete tasks βββ pages/ β βββ TasksPage.tsx β NEW: the task screen (was in App) βββ components/ β βββ LoginForm.tsx β NEW: log in or sign up β βββ TaskForm.tsx TaskList.tsx TaskItem.tsx FilterBar.tsx (unchanged) βββ App.tsx β now: login form or tasks page βββ types.ts
Step 1: Tell React where the API is
Create a .env file in the React project:
VITE_API_URL=http://localhost:3000π‘Only variables starting with VITE_ reach the browser. Restart bun run dev after changing .env.
Step 2: One helper for every request
import type { Task } from "../types";
// The backend's address comes from .env (VITE_API_URL), so it can change without touching code.
const API_URL = import.meta.env.VITE_API_URL;
// One helper for every request: adds JSON headers and the login token, and turns errors into exceptions.
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const token = localStorage.getItem("token");
const res = await fetch(`${API_URL}${path}`, {
...options,
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
});
if (res.status === 204) return undefined as T; // DELETE sends no body
const data = await res.json();
if (!res.ok) throw new Error(data.error ?? "Something went wrong");
return data as T;
}
type AuthResponse = { token: string; user: { id: number; name: string; email: string } };
export const api = {
login: (email: string, password: string) =>
request<AuthResponse>("/api/auth/login", { method: "POST", body: JSON.stringify({ email, password }) }),
register: (name: string, email: string, password: string) =>
request<AuthResponse>("/api/auth/register", { method: "POST", body: JSON.stringify({ name, email, password }) }),
getTasks: () => request<{ tasks: Task[] }>("/api/tasks?limit=50").then((r) => r.tasks),
createTask: (title: string) => request<Task>("/api/tasks", { method: "POST", body: JSON.stringify({ title }) }),
updateTask: (id: number, changes: { title?: string; done?: boolean }) =>
request<Task>(`/api/tasks/${id}`, { method: "PATCH", body: JSON.stringify(changes) }),
deleteTask: (id: number) => request<void>(`/api/tasks/${id}`, { method: "DELETE" }),
};request does the boring parts once: the base URL, JSON headers, the Authorization header with the token, βno bodyβ for DELETE (204), and turning { "error": "β¦" } answers into errors. Each API call is then one line.
Step 3: A custom hook for tasks
This is the useState + useEffect logic from earlier lessons, moved out of the component into a function named useTasks. A function that starts with use and uses hooks is a custom hook.
import { useEffect, useState } from "react";
import type { Task } from "../types";
import { api } from "../api/client";
// A custom hook: all the task logic in one place, so components stay simple.
export function useTasks() {
const [tasks, setTasks] = useState<Task[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
// Load the tasks once, when the page opens.
useEffect(() => {
api
.getTasks()
.then(setTasks)
.catch((err: Error) => setError(err.message))
.finally(() => setLoading(false));
}, []);
async function addTask(title: string) {
try {
const task = await api.createTask(title);
setTasks((current) => [task, ...current]); // newest first, like the API
} catch (err) {
setError((err as Error).message);
}
}
async function toggleTask(id: number) {
const task = tasks.find((t) => t.id === id);
if (!task) return;
try {
const updated = await api.updateTask(id, { done: !task.done });
setTasks((current) => current.map((t) => (t.id === id ? updated : t)));
} catch (err) {
setError((err as Error).message);
}
}
async function deleteTask(id: number) {
try {
await api.deleteTask(id);
setTasks((current) => current.filter((t) => t.id !== id));
} catch (err) {
setError((err as Error).message);
}
}
return { tasks, loading, error, addTask, toggleTask, deleteTask };
}Step 4: The login form
import { useState } from "react";
import { api } from "../api/client";
type Props = {
onLogin: (token: string) => void;
};
// One form for both "log in" and "sign up". Sign up just shows one extra field: name.
export function LoginForm({ onLogin }: Props) {
const [mode, setMode] = useState<"login" | "signup">("login");
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
return (
<form
className="login"
onSubmit={async (e) => {
e.preventDefault();
setError("");
setBusy(true);
try {
const result = mode === "login" ? await api.login(email, password) : await api.register(name, email, password);
onLogin(result.token);
} catch (err) {
setError((err as Error).message);
} finally {
setBusy(false);
}
}}
>
<h1>{mode === "login" ? "Log in" : "Create an account"}</h1>
{mode === "signup" && <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Your name" />}
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="Email" />
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder="Password (8+ characters)" />
{error && <p className="error">{error}</p>}
<button type="submit" disabled={busy}>
{busy ? "Please waitβ¦" : mode === "login" ? "Log in" : "Sign up"}
</button>
<button type="button" className="link" onClick={() => setMode(mode === "login" ? "signup" : "login")}>
{mode === "login" ? "New here? Create an account" : "Already have an account? Log in"}
</button>
</form>
);
}Step 5: The tasks page
It's the old App, but the tasks now come from useTasks, with loading and error states:
import { useState } from "react";
import type { Filter } from "../types";
import { useTasks } from "../hooks/useTasks";
import { TaskForm } from "../components/TaskForm";
import { TaskList } from "../components/TaskList";
import { FilterBar } from "../components/FilterBar";
type Props = {
onLogout: () => void;
};
export function TasksPage({ onLogout }: Props) {
const { tasks, loading, error, addTask, toggleTask, deleteTask } = useTasks();
const [filter, setFilter] = useState<Filter>("all");
const visibleTasks = tasks.filter((t) => (filter === "active" ? !t.done : filter === "done" ? t.done : true));
const left = tasks.filter((t) => !t.done).length;
return (
<main className="app">
<header className="top">
<h1>My To-Do List</h1>
<button className="link" onClick={onLogout}>
Log out
</button>
</header>
<TaskForm onAdd={addTask} />
<FilterBar filter={filter} onChange={setFilter} />
{error && <p className="error">{error}</p>}
{loading ? <p className="empty">Loading your tasksβ¦</p> : <TaskList tasks={visibleTasks} onToggle={toggleTask} onDelete={deleteTask} />}
<p className="count">
{left} {left === 1 ? "task" : "tasks"} left
</p>
</main>
);
}Step 6: App chooses what to show
import { useState } from "react";
import { LoginForm } from "./components/LoginForm";
import { TasksPage } from "./pages/TasksPage";
export default function App() {
// Remember the login token, even after a page reload.
const [token, setToken] = useState(() => localStorage.getItem("token"));
function handleLogin(newToken: string) {
localStorage.setItem("token", newToken);
setToken(newToken);
}
function handleLogout() {
localStorage.removeItem("token");
setToken(null);
}
// No token? Show the login form. Otherwise, show the tasks.
return token ? <TasksPage onLogout={handleLogout} /> : <LoginForm onLogin={handleLogin} />;
}Add a few styles for the login form to the end of src/index.css:
.top { display: flex; justify-content: space-between; align-items: center; }
.login { max-width: 360px; margin: 64px auto; padding: 24px; background: white; border-radius: 16px; display: grid; gap: 10px; box-shadow: 0 4px 24px rgb(0 0 0 / 0.08); }
.login input { padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 8px; font-size: 16px; }
.link { background: transparent; color: #059669; padding: 4px; }
.error { color: #dc2626; }What we tested
We ran the React app against the Node.js API and PostgreSQL in a real browser:
| Action | What happened |
|---|---|
| Sign up | Account created; the app switched straight to the task list |
| Add 3 tasks | Saved in the database; newest shown first |
| Tick a task, then refresh the page | Still ticked: it came back from the database |
| Delete a task | Removed from the list and the database |
| Log out, log in with a wrong password | "Wrong email or password" shown under the form |
| Log in correctly | The same tasks came back |
Key takeaways
- βReact talks to a backend with fetch, wrapped in one small helper.
- βA custom hook (useTasks) keeps data logic out of components.
- βThe login token is saved and sent as Authorization: Bearer <token>.
- βThe app shows the login form or the task page depending on the token.
- βYour full-stack To-Do app is done: React + Express + PostgreSQL.
Frequently asked questions
How does React talk to a backend?
With fetch (built into the browser): send a request to the API's URL, wait for the JSON answer, then put it in state. Wrapping fetch in one helper keeps headers, the login token and error handling in one place.
Where should I keep the login token?
For learning, localStorage is the simplest and very common. Bigger production apps often use an httpOnly cookie set by the server, so page scripts can't read it. Either way, never put secrets in your frontend code.
What is a custom hook?
A normal function whose name starts with use and that calls other hooks (useState, useEffect). It lets you move logic like 'load and change tasks' out of components, so components only show things.
What is CORS and why does it matter here?
Browsers block a page on one address (localhost:5173) from reading answers from another (localhost:3000) unless the server allows it. Our Express API uses the cors() middleware, which allows it.
Why VITE_API_URL in .env?
So the backend address can be different on your laptop and in production without changing code. Vite only exposes variables that start with VITE_ to the browser; read them with import.meta.env.
π§ Quick check: connecting to the backend
1. Which file should know the backend's URL and add the token?
2. Why does useTasks exist?
3. How does App decide between the login form and the task list?
4. Which env variable name will Vite give to your browser code?
Checking your accessβ¦