CodingNic

Transactions

Add the Transaction Update Endpoint

Transactions 22 min read

Add the Transaction Update Endpoint

Editing needs a server operation that changes one existing transaction. Open:

text
server/src/routes/transactions.js
client/src/lib/api.js

Creation uses POST /api/transactions. Editing should identify the existing record by id, so we add PUT /api/transactions/:id.

Add the route beside the existing transaction routes:

javascript
router.put("/:id", async (req, res) => {
  const db = await getDb();
  const index = db.transactions.findIndex(
    (transaction) => transaction.id === req.params.id
  );

  if (index === -1) {
    return res.status(404).json({ error: "Transaction not found" });
  }

  const updated = {
    id: req.params.id,
    date: req.body.date,
    description: req.body.description.trim(),
    category: req.body.category,
    amount: req.body.amount,
    type: req.body.type,
  };

  db.transactions[index] = updated;
  await saveDb();
  res.json(updated);
});

findIndex() gives us the position of the transaction inside the array. We need the position because assignment replaces the existing array item:

javascript
db.transactions[index] = updated;

Keep the original id from req.params.id. The purpose of an edit is to change the existing record, not create a second record with a new identity.

Return the updated transaction. The client can use that response to replace the old object in React state.

Now add the matching API helper:

javascript
export const updateTransaction = (id, entry) =>
  request(`/transactions/${id}`, {
    method: "PUT",
    body: JSON.stringify(entry),
  });

The component still does not call fetch() directly. api.js remains the single place that knows how HTTP requests are made.

Test it

Pick one transaction and send a PUT request for its id using the browser Network panel or an API client.

Change its description, then refresh the browser. The same transaction should contain the new description. There should not be an additional row.

Checkpoint

The server can replace one transaction by id, preserve that transaction’s identity, persist the change, and return the updated record to the client.