Frontend State Management and Form Handling
Data Structure DesignModel answerLast updated
Build a web interface that manages list state, handles form submission with proper error recovery, integrates with APIs, and maintains data consistency.
You're building a web application that demonstrates fundamental frontend engineering skills. Your implementation must handle state correctly, integrate with backend services, and provide a good user experience.
Requirements:
-
List rendering: Display items from an array in memory. Use BEM naming convention with double underscores for CSS classes (e.g.,
component__element). Single underscores should not be used. -
Form handling: Create a form that adds new items to the list. When submission fails (like a 400 error), preserve the user's input and display an error message. When submission succeeds, add the item to the list and clear the form.
-
API integration: Load items from a backend endpoint and display them. Handle three states: loading, success, and error. When merging server data with locally-created items, prevent duplicates.
-
Quality requirements: Implement proper accessibility (associate labels with inputs, use correct button types), ensure operations are idempotent, and make rendering predictable.
Discussion points:
Explain your approach to event handling, state management, and error handling. Describe how you would organize files and components, and how you would test these behaviors.
Hints
Hint 1
Consider what happens when API responses arrive out of order or a user clicks submit multiple times
Hint 2
Think about who owns the form input values—the browser or your rendering logic
Hint 3
Use unique identifiers to reconcile local and server data without creating duplicates
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests a core frontend principle: maintain a single source of truth and derive UI from state. Direct DOM manipulation creates bugs; instead, state changes trigger renders.
The solution uses vanilla JavaScript to demonstrate fundamentals clearly. The same patterns apply to React, Vue, or any framework.
Architecture
State structure:
{
items: [], // list data
status: 'idle', // 'loading' | 'success' | 'error'
loadError: null,
submitting: false,
submitError: null
}
Separation of concerns:
api.js: Network layer, returns normalized errorsstate.js: Pure functions for data transformationsapp.js: State management, event handlers, renderingapp.test.js: Behavior tests with mocked network
In a component framework, split further: separate list and form components, extract data fetching into a custom hook, keep API calls isolated.
Key Implementation Details
1. Unidirectional data flow
Every change follows: event → state update → render. Never manipulate DOM directly from event handlers.
function setState(patch) {
state = { ...state, ...patch };
render();
}
async function load() {
setState({ status: 'loading' });
const data = await fetchItems();
setState({ status: 'success', items: data });
}
2. Form input preservation
Critical: render() never touches input.value. The browser controls form fields. Only form.reset() clears them, and that runs exclusively after successful submission.
form.addEventListener('submit', async (e) => {
e.preventDefault();
try {
await createItem(input.value);
form.reset(); // only clear on success
} catch (err) {
setState({ submitError: err.message });
// input.value unchanged—user can fix and retry
}
});
3. Duplicate prevention through merging
Each item needs a unique id. When reconciling server and local data, merge by key:
function mergeById(primary, secondary) {
const seen = new Map(primary.map(item => [item.id, item]));
for (const item of secondary) {
if (!seen.has(item.id)) {
seen.set(item.id, item);
}
}
return [...seen.values()];
}
// Server data takes precedence; keep local items not yet on server
setState({ items: mergeById(serverItems, state.items) });
4. Race condition handling
Use a sequence counter to discard stale responses:
let fetchSequence = 0;
async function load() {
const seq = ++fetchSequence;
const data = await fetchItems();
if (seq !== fetchSequence) return; // newer fetch already started
setState({ items: data });
}
5. Idempotency
Prevent duplicate submissions:
- Disable button while submitting
- Guard with
state.submittingcheck - Use
Idempotency-Keyheader so retrying a timed-out request doesn't duplicate server records
let idempotencyKey = null;
form.addEventListener('submit', async (e) => {
if (state.submitting) return;
idempotencyKey ??= crypto.randomUUID();
setState({ submitting: true });
try {
await createItem(input.value, idempotencyKey);
idempotencyKey = null; // success—next submit is new intent
} catch (err) {
// keep same key—retry is same intent
}
});
input.addEventListener('input', () => {
idempotencyKey = null; // edited text—new intent
});
Accessibility
- Use semantic HTML:
<form>,<button type="submit">,<ul>,<li> - Associate labels:
<label for="name-input"> - Mark invalid state:
aria-invalid="true"on error - Indicate busy state:
aria-busy="true"during submission - Manage focus: return focus to input after submission
Event Handling Strategy
Listen to the form's submit event, not the button's click. This captures Enter key presses and integrates with browser validation.
Always call preventDefault() to stop page reload. Extract and validate input values within the handler.
For input changes, clear error messages immediately to provide responsive feedback.
Testing Strategy
Unit tests (state.js):
mergeByIdwith overlapping and non-overlapping IDs- Edge cases: empty arrays, all duplicates
Integration tests (app.js with jsdom):
- Mock
fetchresponses - Verify DOM updates after state changes
- Test error paths: network failure, 400 response
- Verify input preservation on error
- Test rapid successive submissions
E2E tests:
- Load items, see loading state then list
- Submit valid item, see it appear
- Submit invalid item, see error and preserved input
- Retry after error
Common Mistakes
- Clearing form on error: Writing
form.reset()in afinallyblock wipes user input - Direct DOM manipulation: Appending
<li>elements in event handlers creates state/UI drift - Missing duplicate prevention: Appending items without checking IDs creates duplicates when API responses overlap
- Ignoring race conditions: Not guarding against out-of-order responses corrupts state
- Listening to button click: Misses Enter key submission
- Single underscore in class names: Using
list_iteminstead oflist__itemfails BEM convention
Complexity
- Time: O(n) per render for n items; O(n+m) for merging n server items with m local items
- Space: O(n) for items array and DOM elements
The bottleneck is typically rendering large lists. For hundreds of items, use virtual scrolling. For thousands, paginate or implement infinite scroll.
Trade-offs
Vanilla JS vs Framework: This solution uses plain JavaScript for clarity. React would reduce boilerplate with hooks and JSX, but the state management principles remain identical.
Optimistic updates: Could immediately add items to the list before the POST completes, then handle rollback on error. This improves perceived performance but complicates error handling.
Normalization: For complex data, consider normalized state (entities by ID, arrays of IDs) to simplify updates and prevent inconsistencies.