Skip to content

Integrate TanStack Query and enhance API error handling - #329

Merged
jeroenrinzema merged 17 commits into
mainfrom
feat/tanstack-query-foundation
Nov 30, 2026
Merged

jeroenrinzema merged 17 commits into
mainfrom
feat/tanstack-query-foundation

Conversation

@IamKirbki

@IamKirbki IamKirbki commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Why

Most of the console's loading and saving bugs come from the same few patterns:

  • Fetching inside useEffect: useEffect + useState with a hand-rolled loading flag, or useResolver, which only logs errors.
  • Unchecked oapiClient errors: oapiClient (openapi-fetch) never throws on 4xx/5xx; it returns { error }. A lot of code only reads data, so a rejected request looks like a success.
  • Missing error handling: the API clients only handle 401 and 403, so every call site has to catch errors itself, and many don't.

This PR only adds the shared pieces needed to fix that area by area. It changes no pages.

Changes

  • TanStack Query (@tanstack/react-query 5.105) with one QueryClient in console/src/lib/query.ts, provided in App.tsx.
    • Queries are considered fresh for 30 s and retry once.
    • Every failed mutation is shown in a toast by the mutation cache: the server's detail when there is one, otherwise the mutation's meta.errorMessage, otherwise a generic message. A save can't fail silently anymore.
    • wasReported(err) lets a caller that also catches an error avoid toasting it twice.
  • unwrap() (console/src/oapi/unwrap.ts) turns an openapi-fetch result into its data, or throws an ApiError carrying the server's problem detail. problemDetail() in utils.ts now reads it, as well as axios errors.
  • useProjectLocales / projectLocalesQuery (console/src/hooks/use-project-locales.ts) load the project's locales once, through the cache, with the API's maximum page size of 100.

Testing

  • src/oapi/unwrap.test.ts covers data, an empty response, an error with a detail, and an error without one.
  • vite build succeeds. No new type errors.

Notes

  • Behaviour is unchanged until a page uses these pieces.

Depends-On: #330 #332 #334 #335 #336 #337

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The editors can overwrite newer server data with stale cached steps or rules and discard attribute edits made while a save is in flight.

3 open issues
1 file not reviewed
  • console/pnpm-lock.yaml: Generated file
What changed in this PR

Introduces shared TanStack Query infrastructure and applies cached loading and explicit error handling across console workflows. The changes support the linked reliability work for users, lists, organizations, journeys, and broadcasts.

Changes:

  • Adds a shared query client, mutation error toasts, API response unwrapping, and cached locale loading.
  • Moves route data and page operations into queries and mutations, with retry states and journey-specific editor state.
  • Extracts smaller components and adds regression tests for failed requests, cache updates, and overlapping searches.
File Description
console/​src/​views/​users/​UserTimezoneEdit.tsx Extracts mutation-backed timezone editing.
console/​src/​views/​users/​Users.test.tsx Tests failed loads and user creation.
console/​src/​views/​users/​UserRoute.tsx Provides cached user data through context.
console/​src/​views/​users/​UserLookup.tsx Adds cached searches and retry handling.
console/​src/​views/​users/​UserDetailSubscriptions.tsx Uses queries and mutations for subscriptions.
console/​src/​views/​users/​UserDetailSubscriptions.test.tsx Tests unsubscribe-all pagination and failures.
console/​src/​views/​users/​UserDetailOrganizations.tsx Adds paged queries and load errors.
console/​src/​views/​users/​UserDetailJourneys.tsx Adds cached journey pages and retry handling.
console/​src/​views/​users/​UserDetailEvents.test.tsx Tests event loading and creation outcomes.
console/​src/​views/​users/​UserDetail.test.tsx Tests cached updates and failed saves/deletes.
console/​src/​views/​users/​pageNumbers.ts Extracts shared pagination calculations.
console/​src/​views/​users/​LoadErrorRow.tsx Adds a reusable error-and-retry table row.
console/​src/​views/​users/​ListUploadDialog.tsx Extracts mutation-backed list uploads.
console/​src/​views/​users/​Lists.test.tsx Tests list loading and action failures.
console/​src/​views/​users/​ListRuleSection.tsx Extracts rule editing and save-state tracking.
console/​src/​views/​users/​ListRow.tsx Extracts list rows and action menus.
console/​src/​views/​users/​ListRoute.tsx Provides cached lists and generation polling.
console/​src/​views/​users/​listQueries.ts Centralizes list queries, mutations, and invalidation.
console/​src/​views/​users/​ListDetail.test.tsx Tests member loading and rule-save state.
console/​src/​views/​users/​ListCreateForm.tsx Uses a mutation for list creation.
console/​src/​views/​users/​CreateUserEventDialog.tsx Extracts event creation with failure handling.
console/​src/​views/​router.tsx Connects entity routes to query-backed providers.
console/​src/​views/​organizations/​testing.tsx Adds shared organization test fixtures and setup.
console/​src/​views/​organizations/​RemoveMemberDialog.tsx Extracts mutation-backed member removal.
console/​src/​views/​organizations/​PageNumbers.tsx Extracts numbered pagination controls.
console/​src/​views/​organizations/​Organizations.test.tsx Tests organization loading and creation.
console/​src/​views/​organizations/​OrganizationDetailMembers.test.tsx Tests member loading, addition, and removal.
console/​src/​views/​organizations/​OrganizationDetailEvents.test.tsx Tests event failures and overlapping searches.
console/​src/​views/​organizations/​OrganizationDetailAttrs.tsx Separates local attribute edits from cached data.
console/​src/​views/​organizations/​OrganizationDetail.tsx Uses mutations for renaming and deletion.
console/​src/​views/​organizations/​OrganizationDetail.test.tsx Tests rename and delete outcomes.
console/​src/​views/​organizations/​Organization.tsx Provides cached organization data to tabs.
console/​src/​views/​organizations/​MemberExpandedRow.tsx Extracts member attribute editing controls.
console/​src/​views/​organizations/​LoadErrorRow.tsx Adds reusable table load-error feedback.
console/​src/​views/​organizations/​EventExpandedRow.tsx Extracts expanded event details.
console/​src/​views/​organizations/​CreateOrganizationEventDialog.tsx Extracts mutation-backed event creation.
console/​src/​views/​organizations/​CreateOrganizationDialog.tsx Extracts organization creation and retry preservation.
console/​src/​views/​journey/​steps/​Campaign.tsx Shares cached campaign lookups between steps.
console/​src/​views/​journey/​steps/​Action.tsx Shares action and metadata queries.
console/​src/​views/​journey/​steps/​Action.test.tsx Tests request sharing across action steps.
console/​src/​views/​journey/​queries.ts Defines journey queries and shared lookups.
console/​src/​views/​journey/​mutations.ts Centralizes journey actions, saves, and publishing.
console/​src/​views/​journey/​JourneyVariableContext.tsx Uses cached variable-path suggestions.
console/​src/​views/​journey/​JourneyUserSelectionModal.tsx Uses search-keyed infinite queries for users.
console/​src/​views/​journey/​JourneyUserSelectionModal.test.tsx Tests overlapping searches and load failures.
console/​src/​views/​journey/​JourneyTipCard.tsx Extracts the journey guidance card.
console/​src/​views/​journey/​Journeys.test.tsx Tests journey loading and mutation outcomes.
console/​src/​views/​journey/​JourneyRow.tsx Extracts journey rows and action menus.
console/​src/​views/​journey/​JourneyRoute.tsx Provides cached journey data through context.
console/​src/​views/​journey/​JourneyForm.tsx Uses mutations for journey creation and updates.
console/​src/​views/​journey/​JourneyDetail.tsx Removes the unused detail wrapper.
console/​src/​views/​journey/​hooks/​useJourneyPersistence.ts Delegates saving and publishing to mutations.
console/​src/​views/​journey/​editor/​JourneyEditor.tsx Isolates editor state by journey and queries steps.
console/​src/​views/​journey/​components/​JourneyLibrarySidebar.tsx Loads cached actions with error and retry UI.
console/​src/​views/​journey/​components/​JourneyEditorToolbar.tsx Uses a mutation for journey renaming.
console/​src/​views/​journey/​components/​JourneyCanvas.tsx Passes project identity to the querying sidebar.
console/​src/​views/​broadcast/​RecipientsPanel.tsx Adds recipient load-error and retry feedback.
console/​src/​views/​broadcast/​CreateBroadcastDialog.test.tsx Tests deferred loading and creation failures.
console/​src/​views/​broadcast/​BroadcastTipCard.tsx Extracts the broadcast guidance card.
console/​src/​views/​broadcast/​Broadcasts.tsx Uses cached list queries and polling.
console/​src/​views/​broadcast/​Broadcasts.test.tsx Tests failed loads and out-of-order pages.
console/​src/​views/​broadcast/​BroadcastDetail.tsx Displays broadcast and recipient load failures.
console/​src/​utils.ts Reads server details from ApiError.
console/​src/​oapi/​unwrap.ts Converts API error results into thrown errors.
console/​src/​oapi/​unwrap.test.ts Tests response unwrapping and error details.
console/​src/​lib/​query.ts Configures caching, retries, and mutation error toasts.
console/​src/​hooks/​use-project-locales.ts Adds shared cached locale loading.
console/​src/​App.tsx Provides the shared query client application-wide.
console/​public/​locales/​en.json Adds loading and mutation failure messages.
console/​pnpm-lock.yaml Locks TanStack Query dependencies.
console/​package.json Adds the TanStack React Query dependency.

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Later-page loading failures are hidden when existing users remain visible, leaving users without an error message or retry option.

No open issues 🎉

1 previously missed issue

In code that hasn't changed since last review

Medium severity Show retry error when loading a later page fails

console/​src/​views/​journey/​JourneyUserSelectionModal.tsx:273

When a later page fails to load, earlier users remain, so the users.length > 0 branch hides this error/Retry branch and the failure is invisible. Show an error footer alongside the existing rows when isFetchNextPageError is true, with Retry calling fetchNextPage(). TanStack's default-branch test at e7916a9, rather than the pinned 5.105.0 source, also shows this retained-data state.

3 resolved since last review
1 file not reviewed
  • console/pnpm-lock.yaml: Generated file

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Failed refreshes with cached data hide errors and Retry controls in both broadcast and recipient tables, leaving stale statuses visible without warning.

No open issues 🎉

2 previously missed issues

In code that hasn't changed since last review

Medium severity Surface broadcast refresh failures with retained rows

console/​src/​views/​broadcast/​Broadcasts.tsx:217

This only shows the failure UI when there is no cached data. Once a page has loaded, a failed polling or focus refresh retains broadcasts, so the table silently keeps showing stale sending/scheduled states without an error or Retry. Check list.isError as well, or display a separate refresh-error banner above the retained rows. TanStack represents this case as isRefetchError (default-branch source).

Medium severity Show refresh errors alongside cached users

console/​src/​views/​broadcast/​RecipientsPanel.tsx:158

After a successful load, a failed live-update or final refresh retains users, so !users hides the error and Retry button while stale recipient statuses remain visible. Render the error row independently of the data rows so cached rows remain visible alongside the failure. TanStack supports errors alongside retained data (default-branch source).

1 file not reviewed
  • console/pnpm-lock.yaml: Generated file

Review effort: Balanced

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 Needs a closer look

Human assessment is needed because the infrastructure-only description conflicts with shipped route and page migrations, leaving the review and release-validation scope unclear.

No open issues 🎉

1 file not reviewed
  • console/pnpm-lock.yaml: Generated file

Review effort: Balanced

IamKirbki and others added 14 commits November 30, 2026 12:31
Shared setup for moving console pages from fetch-in-effect to TanStack
Query, so each area can migrate on its own branch:

- one QueryClient for the app, provided in App.tsx; failed mutations
  are shown in a toast by the mutation cache, so no save fails silently
- unwrap() turns an openapi-fetch { error } into a thrown ApiError,
  since openapi-fetch never throws on HTTP errors; problemDetail reads it
- useProjectLocales / projectLocalesQuery: the project's locales as one
  cached query with the API's maximum page size
…ail page

Reschedule, schedule, remove schedule and cancel ignored the openapi-fetch
error, so a rejected request still showed a success toast. Send showed
nothing at all. They are now mutations that unwrap the response: failures
are toasted by the mutation cache, success toasts only follow an accepted
request, and the broadcast is refetched afterwards.

The broadcast and its recipients load through queries. A failed load shows
an error with Retry instead of an endless skeleton, and the recipients page
and search are part of the query key, so a late response for an older page
or search can't replace the current one. SSE ticks invalidate the
recipients query instead of fetching directly.
The broadcasts list now loads through a query keyed by page and search,
polling with refetchInterval while a broadcast is sending or scheduled.
A failed load shows an error with Retry instead of "No broadcasts yet" or
an endless skeleton. The tip card moves to its own file to keep the page
short.
Campaigns and lists were fetched when the host page mounted, even with
the dialog closed, and never refreshed. They now load through queries
enabled only while the dialog is open and refetch on each opening. A
failed load shows an error with Retry instead of "nothing available".
The create request is a mutation whose failure is toasted by the
mutation cache.
…report failed saves

The organization route now fills the query cache in its loader and the
page reads it with useSuspenseQuery, so a save on one tab is seen by the
header and every other tab instead of a copy of the loader data.

- A failed delete no longer navigates to the list as if it succeeded.
- A failed rename is shown, and the header keeps the saved name.
- The attributes editor only keeps unsaved edits, so it follows the
  cached organization instead of a value seeded once.
…and events pages

The organizations list, members and events now load with useQuery, with
the page and search in the query key, so a slow earlier response can no
longer replace a newer one, a failed load shows an error with Retry
instead of an endless skeleton or "no members", and every create, add,
remove and save goes through a mutation that reports a failure and keeps
its dialog or edits open.

The create dialogs, removal dialog, expanded rows and page-number
pagination move to their own files to keep the pages short.
…d context

Following an entrance link to another journey kept the editor mounted, so
journey B's name showed over journey A's canvas and a save wrote A's steps
into B. The editor is now keyed by journey id and loads its steps from a
query keyed by journey, the route reads the journey from the query cache
(loader + useSuspenseQuery) instead of a copied loader state, and saves,
publishes and renames run as mutations that write the cache and report
failures. The actions sidebar shows a load error with Retry instead of an
endless skeleton. JourneyDetail was unused and is removed.
The journeys list and its archived view use queries keyed by search and
page, so a failed load shows an error with Retry instead of an endless
skeleton and a slow older response can't replace a newer one. Duplicate,
archive, unarchive and create run as mutations whose failures are shown;
a failed create keeps the dialog open. The list route no longer runs an
unused loader request.
…e results

Action and campaign steps read their action, action types and campaign
from shared queries, so a canvas of N steps no longer makes ~2N identical
requests. Path suggestions are one query shared by the variable context,
the entrance editor and the user picker. The entrance list picker and the
user picker key their results by search (the user picker no longer drops
a search typed while the first page loads), the event picker ignores
superseded responses, and all of them show load failures.
…saves

The user pages fetched with useResolver, which only logs a failed request,
and saved with openapi-fetch calls whose `error` was never checked. A
rejected event showed "Event created", a failed subscription change or
"unsubscribe all" looked done, and any failed load left a skeleton up
forever.

- Every fetch is a query keyed by its params (no stale-response races
  when searching or paging) with a Retry row when it fails.
- Every save is a mutation that unwraps openapi-fetch errors, so the
  mutation cache reports failures and dialogs stay open on error.
- "Unsubscribe all" pages through all of the user's subscriptions instead
  of the first 100.
- UserContext is backed by the query cache (route loader +
  useSuspenseQuery), so a save on one tab is seen by the header and the
  other tabs; the unused list loader of the users route is gone.
- Custom attributes keep only a local draft, so they follow the saved
  user until edited and Save sends what is on screen.
- Locale/timezone editors, the device section and the create dialogs move
  to their own files to keep each page under ~400 lines.
- The overview and a list's users are queries keyed by their params, so
  overlapping responses (search, paging, the generation poll) can no longer
  overwrite newer ones. A failed load says so with a Retry instead of an
  endless skeleton or "No users in this list yet".
- Create, duplicate, archive, unarchive, upload and save are mutations:
  failures are reported, dialogs stay open, and nothing rejects into an
  onClick.
- ListContext is backed by the query cache; the list is polled with
  refetchInterval while it generates. The unused list loader of the lists
  route is gone.
- The rule editor clears "Unsaved changes" (and the navigation blocker)
  only after the rule was saved, and saving the name or publishing no
  longer clears the blocker while rule edits are unsaved.
- The row, users table, rule section and upload dialog move to their own
  files to keep the page under ~400 lines.
The shared import dialog already defines user_import_failed with a
trailing period; matching it keeps en.json free of conflicting values
when the branches merge.
- Journey editor waits for a successful steps fetch, so a failed refresh keeps Retry visible
- List rule editor shows the cached rule while clean and keeps only unsaved edits
- Organization attributes keep edits made while a save runs
@jeroenrinzema
jeroenrinzema force-pushed the feat/tanstack-query-foundation branch from 5325f01 to 8ee4460 Compare November 30, 2026 11:33
@jeroenrinzema
jeroenrinzema merged commit 54484e3 into main Nov 30, 2026
7 checks passed
@jeroenrinzema
jeroenrinzema deleted the feat/tanstack-query-foundation branch November 30, 2026 11:42
jeroenrinzema added a commit that referenced this pull request Nov 30, 2026
…surface load/save failures (#328)

* feat(locales): implement project locales fetching and update related components
fix(validation): rename replyTo field to reply_to for consistency
chore(migrations): rename email template replyTo key to reply_to for backend compatibility
refactor(mail): optimize locale fetching in email forms and remove redundant API calls
refactor(push): streamline locale handling in push notification setup
refactor(text): enhance locale management in text template setup

* feat(campaign): enhance campaign editor with error handling and template management

* feat: implement unwrap utility for handling API responses

- Add `unwrap` function to process API responses, throwing `ApiError` for errors.
- Create `ApiError` class to encapsulate error details from API responses.
- Introduce tests for `unwrap` to ensure correct behavior for success and error cases.

feat: enhance campaign management with React Query

- Refactor campaign-related components to use React Query for data fetching and mutation.
- Implement `useUpdateCampaign`, `useCreateTemplate`, and `useUpdateTemplate` hooks for managing campaign templates.
- Update `CampaignDetails` and `CampaignReview` components to utilize new hooks for state management.

fix: improve error handling in campaign template operations

- Update error handling in template creation and update processes to display user-friendly messages.
- Ensure that the campaign cache is updated correctly after mutations.

refactor: streamline template context management

- Introduce `TemplateProvider` to manage template state and context.
- Simplify template selection logic in the `Template` component.

test: add unit tests for campaign queries

- Create tests for campaign mutation hooks to verify correct cache updates and error handling.
- Mock API responses to simulate various scenarios during testing.

chore: clean up unused imports and improve code organization

- Remove unnecessary imports and consolidate related functionalities for better readability.

* fix(campaign): resolve coupling and loading issues in campaign editor templates

* refactor: update form handling and types across campaign templates

- Replaced zod type inference with explicit form value types in Inbox, Email, Push, and Text templates.
- Refactored useInboxForm, useEmailForm, usePushForm, and useTextForm hooks to return specific form types.
- Updated Setup components to use new form value types for better type safety.
- Removed unused imports and cleaned up code for clarity.
- Introduced useEmailTemplateSave hook for managing email template saves.
- Enhanced error handling in send test hooks for better user feedback.
- Removed deprecated template persistence logic.

* Refactor email template editor: separate components for block editing, compile checks, and mode controls

- Removed EmailContentPreview component and its related logic from Setup.tsx.
- Introduced BlockEditorPane for managing block editing UI.
- Added BuilderCompileCheck for handling compile checks in the editor.
- Created separate ModeControls and PreviewToolbar components for better organization.
- Consolidated editor options into a dedicated file.
- Updated CodeEditor to utilize new components and streamline functionality.
- Enhanced enterprise support with lazy loading for block editor.

* fix(campaign): address subscription loading and campaign setup issues in editor

* fix(campaign): add create_default_template option and improve template handling in campaign creation

* fix(campaigns): address Copilot review findings

- Keep html/text in the email template schema so saves don't drop the body
- Remove the UTF-8 BOM from the Postgres init script
- Fail sends of a campaign without templates permanently instead of panicking
- Opt out of the server's default template when the console creates a campaign

* fix(console): address second Copilot review round

- Report a rejected locale-creation request instead of leaving it unhandled
- Send a cleared template sender as the nil UUID, which the server clears on
- Offer Retry on the generic route error page, rerunning the route's loaders

* fix(console): cancel in-flight campaign fetch before writing mutation results

An older campaign request finishing after a save overwrote the saved template
in the cache, so the details page showed stale content again.

* fix(console): keep cached templates when a campaign update returns

A campaign update never changes templates, and its response could be older
than a template save made while it was in flight.

* fix(console): drop router imports left over from rebasing onto #329

---------

Co-authored-by: Jeroen Rinzema <jeroen@rinzema.dev>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants