smartyfy.mrindigi.com

Web Development Pro | Lesson 040 | Data Project: A Resilient Events Directory

Web Development Pro · Lesson 40 of 60

Module 4: Data, modules, and state

In this lesson

Prerequisites and learning outcomes

Complete lesson 39 first. This lesson builds on data loading and state integration. By the end, you can deliver a resilient searchable directory backed by local JSON and shareable filters. Plan 10–15 minutes for the core explanation and additional time for the worked practice.

Assemble a resilient local directory

This project combines loading, validation, state, rendering, URL history, and harmless persistence into one workshop directory. A visitor can search titles, choose a category, share the resulting URL, reload data, cancel loading, and explicitly save or apply a category preference. Every record is fictional, and the application performs only local read-only data loading.

The reference folder is self-contained. It includes index.html, styles.css, workshops.json, and modules for validation, state, preferences, URL handling, request ownership, rendering, and entry wiring. Relative paths keep those dependencies portable. Serve the folder with an existing local HTTP server as in lesson 31; no account, package installation, or external deployment is required.

State the precedence rules before coding

The current URL determines the initial query and category, including the all default when a parameter is absent. A saved device preference never silently overrides that shared-link meaning. The visitor can choose “Use saved category” to apply it explicitly. Saving stores only the applied category, not the query, event records, or personal data.

The form fields can contain drafts while the state holds the last applied filters. Data reloads update results without overwriting unfinished typing. Submission, clear, history navigation, and explicit preference application synchronize the controls because those actions deliberately choose a committed view. These rules prevent subtle conflicts between otherwise correct individual modules.

Keep the data path explicit

The loader fetches workshops.json with the current AbortSignal, checks response.ok, parses JSON, and validates every record. Only normalized records enter ready state. A failed fetch or invalid payload enters error state; it is not represented as a successful empty list. An empty valid array is a distinct ready state with zero results.

async function load(signal) {
  const response = await fetch('./workshops.json', { signal });
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return parseWorkshops(await response.json());
}
function acceptLoad(next) {
  state = {
    ...state,
    phase: next.phase,
    items: next.phase === 'ready' ? next.items : [],
    error: next.phase === 'error' ? next.message : ''
  };
  renderDirectory(state, elements);
}
const loader = createLatestLoader(load, acceptLoad);

These functions appear in the supplied app.mjs after imports, element checks, and state initialization. All imported helpers are included in the folder. CreateLatestLoader retains the cancellation and request-id protections from lesson 34, so stale success or failure cannot overwrite the current request's state.

Render one coherent view

RenderDirectory derives visible records from the current query and category only when phase is ready. It creates safe text nodes, replaces the owned result list, updates the result count, and controls the empty message. Loading, error, and canceled states have their own messages and do not show a misleading successful count.

The form remains outside the replaced list, preserving its element identity. Render does not install listeners, write storage, or push history. Those side effects belong to explicit handlers. Keeping rendering focused makes repeated calls predictable and reduces the chance that a harmless refresh creates another history entry or saves a preference unexpectedly.

The HTML includes a readable fallback list for when JavaScript is unavailable. Once the script starts loading fresh local data, the active status describes that process. The stylesheet supplies a narrow-first layout, wrapping controls, readable text, and visible focus styles. Actual rendering remains a manual verification gate in this environment.

Connect actions with bounded effects

Submit reads the controls, normalizes filters, pushes a same-origin URL, and renders. Clear resets the filters, updates the URL, restores all available records, and focuses the search field. Popstate reads location and restores the view without pushing another entry. Reload starts a new owned load; Cancel invalidates the current one.

Save category writes only the applied category under the namespaced preference key and reports whether persistence succeeded. Use saved category reads the supported record or default, applies it deliberately, and updates the URL so the resulting view remains shareable. Clear saved category removes only that key and reports failure honestly if removal was unavailable.

These actions should not fabricate a booking or contact an organizer. The interface repeatedly identifies the data as fictional. A future registration service would be a separate feature with server validation, authorization, delivery, privacy, and duplicate-submission requirements, not a small hidden extension to this static demo.

Test important interrupted journeys

Test initial load, title search, combined category filtering, zero results, clear, and repeated submission. Then test a reload that fails, a retry that succeeds, cancellation, and two overlapping loads resolving out of order. Verify that a data completion does not erase a draft query typed while loading.

For URL behavior, load a filtered URL directly and simulate Back or Forward restoration. For storage, test blocked access, corrupted data, unknown versions, save failure, and targeted removal. Check that a stored repair preference does not override a shared URL whose category defaults to all. These cases turn precedence decisions into observable contracts.

The package runs native module and pure-function tests, controlled fetch and history fixtures, and an explicit limited DOM double against the integrated entry. Static checks inspect the actual files and relative references. No browser, real HTTP server, native validation, layout, or assistive technology ran during authoring; those checks remain clearly marked pending.

Prepare a reviewable milestone

Include a README explaining local serving, the module responsibilities, the search rule, preference precedence, and known limits. A test report should separate passed automated contracts from unrun manual browser checks. Keep a list of exact manual journeys so another person can reproduce them without guessing what “test the site” means.

This is the end of the core implementation unit, not proof of a public production release. The next lessons examine debugging, testing depth, accessibility, performance, security, privacy, and delivery before the final capstone. Preserve this milestone so later quality improvements can be compared with a known functional contract.

Worked practice

Worked exercise 1: Preserve a shared link

Task: The device saved repair, but a shared URL has no category parameter. Worked answer: initialize category all from the URL contract. Apply repair only if the visitor explicitly chooses Use saved category. The same link should not silently select different initial filters on different devices.

Worked exercise 2: Recover from invalid data

Task: A reload returns two records with the same id. Worked answer: validation rejects the payload and the interface enters error state with a retry route. Do not silently show a partial list as complete or reuse stale records under a fresh-success message.

Worked exercise 3: Protect unfinished typing

Task: The visitor types “mend” while a reload is pending. Worked answer: the load completion updates results from committed state but leaves the draft field untouched. On submit, the draft becomes the committed query and the URL and results update together.

Knowledge check

Question 1

Which source determines initial filters in this project? A) The URL, including its defined defaults. B) A saved preference regardless of the link. C) The last category the browser happened to display. D) The first record's category.

Check question 1: answer and explanation

Answer: A. Explicit precedence makes shared links predictable.

Question 2

When may validated records enter ready state? A) As soon as fetch returns any response. B) After status, JSON parsing, and schema checks succeed. C) After the response body is accepted solely because its Content-Type says JSON. D) Before duplicate ids are checked.

Check question 2: answer and explanation

Answer: B. Each boundary answers a different correctness question.

Question 3

Which effect belongs outside the renderer? A) Deriving visible rows. B) Updating count text. C) Pushing a new history entry. D) Showing the empty message.

Check question 3: answer and explanation

Answer: C. History changes should follow explicit actions, not every render call.

Question 4

What should a failed load display? A) A fabricated zero-result success. B) Old data labeled fresh. C) An endless loading state. D) A distinct error state with a useful retry path.

Check question 4: answer and explanation

Answer: D. Failure and valid emptiness have different meanings.

Question 5

What remains before claiming the full visitor experience is verified? A) Real browser rendering, keyboard, history, and accessibility review. B) Treat modeled popstate calls as real Back/Forward verification. C) Treat assigned status text as an observed screen-reader announcement. D) Treat a focus method call as proof of visible keyboard focus.

Check question 5: answer and explanation

Answer: A. The automated contracts are valuable but intentionally narrower than end-to-end browser evidence.

Sources and further reading