Clean state in a card UI: stop writing spaghetti code

# Clean state in a card UI

Date: 19 November 2026

Problem

A card with a button looks simple. The code behind it usually is not.

This article uses a real case. A suburb card lists participants. Each participant has an Enrol button. A second button enrols everyone on the page.

The first version worked. Then it grew:

  • The button held one state in a data-enrol attribute.
  • It held the same state again in its label text.
  • It held the same state again in a CSS class.
  • It held the same state again in disabled.
  • The warning icon lived in a different element and needed its own update.
  • Every click fetched the whole card list again.

Five copies of one fact. That is how a small button becomes fragile code.

Rule 1: Let the element hold state, and let CSS draw it

An attribute is a fact. A class is a style. Do not mix them.

<button class="enrol-toggle"
        data-enrol="false"
        data-state="idle">Enrol</button>
  • data-enrol is the durable fact: is this person enrolled in this round?
  • data-state is the transient fact: idle, saving, saved, failed.

CSS reads the state and draws the result:

.enrol-toggle::before {
    content: "";
    position: absolute;
    left: 0; top: 0; bottom: 0;
    border-left: 3px dotted transparent;
}

.enrol-toggle[data-state="saving"]::before {
    border-left-color: #337ab7;
    animation: enrol-progress 1s linear infinite;
}

.enrol-toggle[data-state="failed"]::before {
    border-left-color: #d9534f;
}

The script sets one attribute. It never touches a style, a colour, or a class. The visual rule stays in one file. A designer can change it without reading JavaScript.

Add prefers-reduced-motion when you animate. Some users must not see motion.

@media (prefers-reduced-motion: reduce) {
    .enrol-toggle[data-state="saving"]::before { animation: none; }
}

Rule 2: Do not store the same fact twice

Keep transient state in the closure, not in the markup. A request is pending or it is not. The button already shows that through data-state and disabled. A third copy named data-pending only creates a way to disagree.

Keep durable state in one place. If the server owns it, the server writes it.

Rule 3: Let the server render the settled state

The first version patched the browser by hand:

  • Set the label text.
  • Swap the button class.
  • Add or remove the warning icon.
  • Change the tooltip.
  • Remove the row when the person no longer belongs on the card.

Each line knew a fact that the view model already knew. Every future change had to be made twice.

Move the row into a partial:

@* Views/DashBoard/_ParticipantCell.cshtml *@
<span class="round-cell" data-key="@Model.Key">
    @* badge, warning icon, enrol button *@
</span>

The card renders it on first paint:

@Html.Partial("_ParticipantCell", cell)

The action returns the same partial after a change:

return Content(RenderParticipantCell(personId, roundId), "text/html");

The script does one thing:

cell.replaceWith(html);

No label logic. No icon logic. No class logic. One template serves first paint and every later update. They cannot drift apart.

Rule 4: A response must carry the truth, not a summary

The batch action first returned a count:

{ "enrolled": 3 }

The script then assumed that every requested pair had succeeded. That assumption breaks when one pair is already enrolled, or when one round is not valid.

Return the state of each pair:

{
  "enrolled": 3,
  "cells": {
    "42:7": "<span class=\"round-cell\" ...>...</span>",
    "43:7": ""
  }
}

An empty cell means the participant no longer belongs on this card. The server decides that rule, not the browser. The script only applies the result.

Rule 5: One request per user action

A single click must not fetch the whole page. The first version reloaded every card, so one toggle waited for every suburb.

The fix here:

  • One POST per click.
  • The POST returns the cell.
  • Only that cell is replaced.

For a bulk action, keep one batch POST. Do not fire one request per button. Concurrent writes to one database cause lock contention and partial failure. One transaction is easier to reason about, easier to retry, and faster.

Rule 6: Make the boundaries explicit

Cards load without the viewport. A card that is off screen still needs data. The lazy loader that waits for scrolling hides state, and it hides failures.

The version here loads every card immediately and reports progress in one bar. Each card counts once, so a retry cannot pass 100 percent. A failure keeps a Retry control.

Rule 7: Show only controls that have a meaning

The enrolment buttons appear only when one round is selected. With two rounds selected, one participant has two membership states, so a single button has no clear meaning.

The rule lives in the controller:

ViewBag.AllowEnrolmentControls = selectedRoundIds.Length == 1;

The view asks one question. It does not inspect the round list in three places.

Rule 8: Test behaviour, not pixels

Assert the facts a user depends on:

  • The database row exists after Save, and survives a reload.
  • The warning appears only for a real mismatch, checked against SQL.
  • A failed save leaves the button usable.
  • A single click sends one POST and no document navigation.

Do not assert a label colour. Do not assert that a class named btn-primary exists. Those are style choices. When you test a style, a redesign breaks your test and tells you nothing about the product.

Rule 9: Delete the duplicate code that a refactor exposes

The refactor removed a 31 line function. Its only job was to rebuild in the browser what the view already knew.

After you move rendering to the server, search for:

  • Functions that set text from a flag.
  • Functions that toggle a class from a flag.
  • Functions that add and remove the same element.

If the answer is already in the model, delete the function.

Result

Item Before After
Copies of the enrolment fact 5 2 (data-enrol, server row)
Requests per single click 1 POST + every card 1 POST
Places that know the warning rule 2 1
Script lines for enrolment about 110 about 70
Tests that read CSS yes no

Practical order of work

  1. Move the row markup into a partial. Render it in both places.
  2. Make the action return the partial.
  3. Replace the manual DOM code with one swap.
  4. Add data-state and move the busy visual into CSS.
  5. Return per-pair results from a batch action.
  6. Delete the code that no longer has a job.

Do one step, then run the browser tests. Each step is small enough to verify alone.

Summary

  • The element holds the state. CSS draws it.
  • The server renders the settled state. The browser swaps it.
  • A response carries the fact for each item, not a summary.
  • One user action makes one request.
  • A rule lives in one place, and the view asks one question.
  • Tests assert behaviour and data, not CSS.

None of these rules need a framework. They need a decision about where each fact lives. Make that decision once and the code stops growing sideways.

Leave a Reply

Your email address will not be published. Required fields are marked *