Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 41 ยท Projects and Practice

Project: An Async Data Dashboard

Build the data layer of a dashboard in Redux: per-widget loading states, request ids to ignore stale responses, a freshness cache, retries with backoff, and polling, all runnable.

A dashboard shows several independent panels: sales, visitors, a list of recent orders. Each loads its own data, may fail on its own, can be refreshed, and must never show a late response from an old request. This project builds that data layer in Redux. It uses the same ideas that RTK Query automates (RTK Query basics), which makes it a good way to understand what the library does for you.

Everything runs in the editors on a stand-in store with a fake, slow, sometimes failing API.

The requirements

  1. Three widgets: sales, visitors, orders. Each has its own status (idle | loading | succeeded | failed), data and error.
  2. Loading a widget that is already fresh (loaded less than 30 seconds ago) is skipped, unless the user forces a refresh.
  3. If two requests for the same widget overlap, only the newest one may update the state.
  4. A failed request can be retried automatically with exponential backoff.
  5. A "refresh all" button and optional polling.
stateDiagram-v2
  [*] --> idle
  idle --> loading: load
  loading --> succeeded: fulfilled (latest request)
  loading --> failed: rejected (latest request)
  succeeded --> loading: refresh
  failed --> loading: retry

The status machine of each widget.

State shape

State is keyed by widget name, so one reducer handles all of them:

JavaScript
{
  widgets: {
    sales:    { status: 'idle', data: null, error: null, requestId: null, loadedAt: null },
    visitors: { status: 'idle', ... },
    orders:   { status: 'idle', ... },
  }
}

requestId records which request currently "owns" the widget. A response is applied only if its id matches, which is how stale responses are dropped.

Step 1: the slice and the stale-response guard

JS Per-widget state with request ids

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The slow first request resolves after the fast second one, but its requestId no longer matches, so the reducer ignores it. Without the guard the screen would end on old numbers, a classic race condition (React async patterns shows the same bug without Redux).

Step 2: freshness and refresh

A thunk can read the state and skip work. We keep a loadedAt timestamp and a maxAge.

JS Skip fresh data, force a refresh

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In Redux Toolkit you would put the freshness rule in createAsyncThunk's condition option so no pending action is dispatched when the call is skipped (createAsyncThunk). Time (Date.now()) is read in the thunk, never in the reducer, so reducers stay pure.

Step 3: retries with exponential backoff

Networks fail transiently. Retrying immediately makes overload worse; waiting longer after every failure ("backoff") is polite and effective. Add a little random jitter so many clients do not retry in lockstep.

JS Retry with backoff

Press Run (or Ctrl + Enter) to see the console output here.

No output.

RTK Query includes this: retry from @reduxjs/toolkit/query wraps a base query with configurable attempts and backoff.

Step 4: refresh all and polling

"Refresh all" is Promise.allSettled over the widgets, so one failing widget does not stop the others, and the UI shows partial success. Polling is a timer that dispatches the same thunk; it must be cleaned up.

JavaScript
// Real Redux Toolkit style (read-only)
export const refreshAll = () => async (dispatch) => {
  const results = await Promise.allSettled(
    ['sales', 'visitors', 'orders'].map((w) => dispatch(loadWidget({ widget: w, force: true }))),
  );
  return results.filter((r) => r.status === 'rejected').length;   // number of failed widgets
};

// In a component (React): poll while mounted
useEffect(() => {
  const id = setInterval(() => dispatch(loadWidget({ widget: 'sales' })), 15000);
  return () => clearInterval(id);       // cleanup on unmount
}, [dispatch]);

With RTK Query the same is useGetSalesQuery(undefined, { pollingInterval: 15000 }), and subscriptions clean up automatically. For production dashboards, prefer RTK Query and keep this hand-built version as the model of what happens inside.

Design notes

  • Per-widget status avoids a single global spinner. Each panel shows its own skeleton or error with a retry button.
  • Keep old data while refreshing (status: 'loading' but data retained) to avoid flicker; show a subtle indicator instead.
  • Selectors return { data, status, error } per widget. Avoid selecting the whole widgets object in each panel.
  • Abort requests on unmount or when parameters change; with fetch, pass an AbortSignal (createAsyncThunk provides one).
  • Test the race by faking the API with controlled promises, as in step 1, and asserting the final state (testing).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does the reducer ignore a stale response?

    Only the request that currently owns the widget may write its result.
  2. 2. Why read the current time in the thunk instead of the reducer?

    A reducer that reads the clock would replay differently.
  3. 3. Which errors should usually NOT be retried?

    A client error will not fix itself; retrying wastes time.
  4. 4. Why use Promise.allSettled for refresh all?

    allSettled waits for every result, whether fulfilled or rejected.

Summary

  • Give each widget its own status, data, error and requestId.
  • Ignore responses whose request id no longer matches.
  • Decide freshness in the thunk (or condition), never in the reducer.
  • Retry transient failures with exponential backoff; do not retry client errors.
  • Refresh with Promise.allSettled, poll with a cleaned-up timer, and prefer RTK Query for production.

Next: Redux practice exercises