Connect Creation Through the Shared Data Layer
Open these files:
client/src/lib/api.js
client/src/context/BudgetContext.jsx
client/src/components/EntryForm.jsx
The starter already contains the beginning of the create workflow. Your task is to make the responsibility of each layer explicit instead of putting the network request inside the form component.
The API helper sends the entry to the server:
export const addTransaction = (entry) =>
request("/transactions", {
method: "POST",
body: JSON.stringify(entry),
});
api.js knows that creation is a POST request. It does not know anything about React state or how the form is displayed.
BudgetContext receives the server response and updates the shared transaction collection:
async function addTransaction(entry) {
const created = await api.addTransaction(entry);
setTransactions((previous) => [...previous, created]);
return created;
}
The sequence is important:
- Wait for the server to accept the record.
- Use the returned object rather than guessing what the server stored.
- Add that object to the shared React collection.
- Return it to the caller for later workflows such as undo.
The form should call the context method, not fetch() directly:
await addTransaction(entry);
Build the request object from the values in the controlled form:
const entry = {
date: form.date,
description: form.description.trim(),
category: form.type === "income" ? "Income" : form.category,
amount: Number(form.amount),
type: form.type,
};
At this point in the course, the starter still uses decimal amount values and the temporary Income category text. Module 5 changes the income category model, and Module 6 changes money to integer cents. Knowing that now prevents a later lesson from looking like an unexplained rewrite.
Only clear the reusable fields after the request succeeds:
setForm((current) => ({
...current,
description: "",
amount: "",
}));
That lets a user enter several records with the same date, type, and category without reselecting everything.
Test it
Add a small expense and confirm that the new row appears immediately.
Refresh the page. The row should still exist because the server stored it in server/data/db.json; the React state alone cannot survive a refresh.
Checkpoint
You can trace the create workflow from the form to BudgetContext, through api.js, into POST /api/transactions, and back into the shared transaction list.