UNPKG

@softr/sdk

Version:

The SDK for building Softr apps on TanStack Start. It lets an app interact with Softr: auth, datasources, workflows and integrations.

256 lines (176 loc) • 11.7 kB
--- name: formatting description: >- Show dates, times and numbers in the app's format without hydration mismatches: FormattedDate, useFormatting with formatDate, formatDateTime and formatNumber, FormattingScope and timeZone, and why toLocaleDateString and Intl defaults must never run in render. metadata: type: sub-skill library: softr-sdk library_version: 1.4.1 --- # Dates, times and numbers Softr stores every date and time as UTC. The builder chooses in Studio how the app shows dates, times and numbers: in each visitor's own format and zone (the default), or in one fixed format or zone for everyone. The SDK resolves that choice once per request. The server and the browser then format with the same values, so the page the server renders and the page the browser hydrates show the same text. > **CRITICAL**: Never call `toLocaleDateString`, `toLocaleTimeString`, `toLocaleString` or `new Intl.DateTimeFormat` / `new Intl.NumberFormat` in code that renders. The server and the browser have different locales and time zones, so the text differs and React throws a hydration mismatch. A hard-coded `'en-US'` or `timeZone: 'UTC'` hides the error but ignores the builder's settings and shows the wrong format and day to most visitors. > > **CRITICAL**: Format with the helpers below and nothing else. They follow the app's settings, and they are the only formatters that give the same text on the server and in the browser. ## Setup ```ts import { FormattedDate, FormattingScope, useFormatting, formatDate, formatDateTime, formatNumber } from '@softr/sdk' import type { Formatting, DateValue, DateOptions } from '@softr/sdk' ``` ```ts type DateValue = Date | number | string // a record's date field works as is; null and undefined are accepted too and show nothing type Formatting = { dateLocale: string numberLocale: string timeZone: string | null // null until the visitor's zone is known fixedDate: { format: 'FRIENDLY' | 'DD-MM-YYYY' | 'MM-DD-YYYY' | 'YYYY-MM-DD'; separator: '-' | '/' | '.'; hour12: boolean } | null weekStart: 1 | 2 | 3 | 4 | 5 | 6 | 7 | null // 1 is Monday; null means the locale's own language: string rtl: boolean } type DateOptions = { dateStyle?: 'short' | 'medium' | 'long' | 'full' parts?: { weekday?, year?, month?, day?, hour?, minute?, timeZoneName? } // only these seven keys timeZone?: string // IANA, such as 'America/New_York' } ``` ## Core Patterns ### A date in JSX: `<FormattedDate />` ```tsx <FormattedDate value={bug.fields.created} /> <FormattedDate value={event.fields.starts} time /> <FormattedDate value={task.fields.due} dateStyle="medium" /> ``` A timestamp (`DATETIME`, `CREATED_AT`, `UPDATED_AT`) is a UTC instant and needs a time zone. On a visitor's first page load their zone can be unknown, and then `FormattedDate` renders its `fallback` (nothing by default) until the browser supplies it. A calendar day (`DATE`, such as `2026-10-06`) names the same day everywhere and always renders at once. `dateStyle` applies only when the app uses the visitor's format; a fixed format ignores it. There is no `timeStyle`. `time` and `formatDateTime` add the time in the app's style, with or without `dateStyle`. For the time alone, use `parts`. ### Part of a date: `parts` A list already filtered to this year needs only the month. A schedule needs only the time. `parts` takes seven keys, with their `Intl` values: `weekday`, `year`, `month`, `day`, `hour`, `minute` and `timeZoneName`. Nothing else, so no `dateStyle`, `timeStyle` or `hour12`. It wins over `dateStyle` and the app's fixed format. The locale and the zone still come from the app. ```tsx <FormattedDate value={post.fields.published} parts={{ month: 'long', year: 'numeric' }} /> // October 2026 <FormattedDate value={shift.fields.starts} parts={{ weekday: 'long' }} /> // Monday <FormattedDate value={shift.fields.starts} parts={{ hour: 'numeric', minute: 'numeric' }} /> // 14:30 ``` The format functions take the same keys inside `parts`, never at the top level: ```ts formatDate(post.fields.published, formatting, { parts: { month: 'long', year: 'numeric' } }) ``` ### A zone or a locale the user names "Show this page in New York time" or "use German formatting here" is a fixed value. It wins over the visitor's and the app's settings. A date in a named zone renders on the server at once, with no fallback. For a page or an area, wrap it in `FormattingScope`. Every `FormattedDate` and `useFormatting()` inside reads the scope. An inner scope wins over an outer one. ```tsx <FormattingScope timeZone="America/New_York"> <EventList events={events} /> </FormattingScope> ``` For one value, pass `timeZone`. It wins over a scope. Use it for an event that shows in its own zone, from a record field or a DATETIME field whose `options` in the datasource schema name a `timezone` and a `timezoneType` other than `LOCAL`. ```tsx <FormattedDate value={event.fields.starts} time timeZone={event.fields.zone} /> ``` Say which zone a fixed-zone time is in, so a visitor elsewhere does not read it as theirs: add `timeZoneName: 'short'` to `parts`, or write the zone next to it. An unknown zone or locale is ignored with a warning, so a bad record never breaks the page. ### Text outside JSX: `useFormatting()` and the format functions Use these for a string prop, an `aria-label`, a chart axis, or a sort key shown to the visitor. ```tsx function BugRow({ bug }: { bug: Bug }) { const formatting = useFormatting() return ( <li title={`Created ${formatDateTime(bug.fields.created, formatting)}`}> {bug.fields.title} <span>{formatNumber(bug.fields.votes, formatting)}</span> </li> ) } ``` `formatNumber` takes the `Intl.NumberFormat` options, for percentages and currencies: ```ts formatNumber(0.25, formatting, { style: 'percent' }) formatNumber(99, formatting, { style: 'currency', currency: 'EUR' }) ``` The currency comes from the field or from the user, never from the locale. A German visitor looking at a price in dollars still sees dollars. `formatDate` and `formatDateTime` show a timestamp in UTC while `formatting.timeZone` is `null`. In JSX, prefer `<FormattedDate />`, which waits instead. A `null` or `undefined` value returns `''` from the functions and renders nothing from `<FormattedDate />`, so a record's nullable date field needs no guard. ### A field's own text: `formatValue` A value a query read already knows how it should look: money with its symbol and cents, a percent, a rating out of its scale, a duration in hours and minutes, a date in the app's format, a choice or a linked record by its label, a checkbox as Yes or No, several values joined by a comma, `''` for nothing. `formatValue` reads the field's type and options from the generated `src/softr-fields.ts` and does all of it, so a page never branches on a type itself. ```tsx import { formatValue, useFormatting } from '@softr/sdk' import { dealsQuery } from '#/server/deals.ts' function Amount({ deal }: { deal: Deal }) { const formatting = useFormatting() return <span>{formatValue(dealsQuery, 'amount', deal.fields.amount, formatting)}</span> } ``` The second argument is the alias the query holds the field under. `formatField(shape, value, formatting)` does the same for a shape in hand, and `fieldShape(query, alias)` reads one. The SDK's codegen writes `src/softr-fields.ts` beside `softr-env.d.ts` after every schema change; it registers the shapes as a side effect of being imported, and the root route imports it once. `formatValue` throws when that import is missing. ### Outside render: a server function or `beforeLoad` Not every date ends up in a component. A CSV or spreadsheet export, a text the server sends, or a value a loader prepares are formatted before React runs. There, `context.formatting` holds the same `Formatting` that `useFormatting()` returns. See [current-user](../current-user/SKILL.md) for how `context` reaches a handler. ```ts import { createServerFn } from '@tanstack/react-start' import { formatDateTime } from '@softr/sdk' const exportBugs = createServerFn().handler(async ({ context }) => { const bugs = await getBugs() return bugs.map((bug) => `${bug.fields.title},${formatDateTime(bug.fields.created, context.formatting)}`).join('\n') }) ``` On a visitor's first page load, `context.formatting.timeZone` is `null`, so a timestamp reads in UTC. Only the browser can fill in the zone. ### A range, or any other `Intl` format For a shape the helpers do not give, such as a range (`Oct 6 – 8`), use `Intl` with the values from `useFormatting()` and never the runtime's defaults. Render it only when the zone is known: ```tsx const formatting = useFormatting() const range = formatting.timeZone === null ? null : new Intl.DateTimeFormat(formatting.dateLocale, { month: 'short', day: 'numeric', timeZone: formatting.timeZone }) .formatRange(new Date(trip.fields.starts), new Date(trip.fields.ends)) ``` ### Relative time and now "3 hours ago" and the current time depend on the moment of rendering, which differs between the server and the browser. Render them only after mount, with `Intl.RelativeTimeFormat` and `formatting.dateLocale`. ### Writing a date back A write takes an ISO string, never a `Date`. A timestamp is written as a UTC instant (`toISOString()`), a day as `YYYY-MM-DD`. See [record-mutations](../record-mutations/SKILL.md). ### A calendar's first day Pass `formatting.weekStart` to a date picker or calendar when it is not `null`. Most take Sunday as `0`: use `formatting.weekStart % 7`. ## Common Mistakes ### CRITICAL: Formatting with the runtime's locale in render Wrong: ```tsx <span>{new Date(bug.fields.created).toLocaleDateString()}</span> ``` Correct: ```tsx <FormattedDate value={bug.fields.created} /> ``` The server renders `10/6/2026` and a browser in Europe renders `06/10/2026`. React rejects the page, and the builder's date settings are ignored on both sides. ### HIGH: Forcing one locale or zone to silence the mismatch Wrong: ```tsx new Intl.DateTimeFormat('en-US', { dateStyle: 'medium', timeZone: 'UTC' }).format(new Date(value)) ``` Correct: ```tsx <FormattedDate value={value} dateStyle="medium" /> ``` The mismatch goes away, but every visitor sees US dates in UTC. A timestamp late in the evening shows the next day. When the user names a zone or a locale, pass it with `timeZone` or `FormattingScope`. ### HIGH: Raw `Intl` while the zone is unknown Wrong: ```tsx const formatting = useFormatting() new Intl.DateTimeFormat(formatting.dateLocale, { timeZone: formatting.timeZone ?? undefined }).format(new Date(value)) ``` Correct: ```tsx <FormattedDate value={value} /> ``` On a first visit `formatting.timeZone` is `null`. `undefined` makes the server use its own zone and the browser use the visitor's, so the text differs and hydration fails. Use the helpers, or render nothing until the zone is known. ### HIGH: Passing `Intl` options the helpers do not take Wrong: ```ts formatDateTime(shift.fields.starts, formatting, { dateStyle: 'medium', timeStyle: 'short' }) formatDate(post.fields.published, formatting, { month: 'long', year: 'numeric' }) ``` Correct: ```ts formatDateTime(shift.fields.starts, formatting, { dateStyle: 'medium' }) formatDate(post.fields.published, formatting, { parts: { month: 'long', year: 'numeric' } }) ``` The options are `dateStyle`, `parts` and `timeZone`, not `Intl.DateTimeFormatOptions`. Anything else fails the type check. `formatDateTime` adds the time itself, and the date parts go inside `parts`. ## References - [SKILL.md](../SKILL.md): the entrypoints and which one each export lives on