You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Integrate TanStack Query and enhance API error handling - #329
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.
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.
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.
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
Surface broadcast refresh failures with retained rows
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).
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).
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.
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
…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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Why
Most of the console's loading and saving bugs come from the same few patterns:
useEffect:useEffect+useStatewith a hand-rolled loading flag, oruseResolver, which only logs errors.oapiClienterrors:oapiClient(openapi-fetch) never throws on 4xx/5xx; it returns{ error }. A lot of code only readsdata, so a rejected request looks like a success.This PR only adds the shared pieces needed to fix that area by area. It changes no pages.
Changes
@tanstack/react-query5.105) with oneQueryClientinconsole/src/lib/query.ts, provided inApp.tsx.detailwhen there is one, otherwise the mutation'smeta.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 anApiErrorcarrying the server's problemdetail.problemDetail()inutils.tsnow 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.tscovers data, an empty response, an error with a detail, and an error without one.vite buildsucceeds. No new type errors.Notes
Depends-On: #330 #332 #334 #335 #336 #337