Get localized error messages.

This commit is contained in:
Mike Cao 2025-09-14 23:43:22 -07:00
parent baba06c692
commit fc01ee9f56
32 changed files with 90 additions and 85 deletions

View file

@ -1,6 +1,6 @@
{ {
"name": "@umami/components", "name": "@umami/components",
"version": "0.121.0", "version": "0.122.0",
"description": "Umami React components.", "description": "Umami React components.",
"author": "Mike Cao <mike@mikecao.com>", "author": "Mike Cao <mike@mikecao.com>",
"license": "MIT", "license": "MIT",

View file

@ -14,7 +14,7 @@ import { ROLES } from '@/lib/constants';
export function UserAddForm({ onSave, onClose }) { export function UserAddForm({ onSave, onClose }) {
const { mutate, error, isPending } = useUpdateQuery(`/users`); const { mutate, error, isPending } = useUpdateQuery(`/users`);
const { formatMessage, labels } = useMessages(); const { formatMessage, labels, getErrorMessage } = useMessages();
const handleSubmit = async (data: any) => { const handleSubmit = async (data: any) => {
mutate(data, { mutate(data, {
@ -26,7 +26,7 @@ export function UserAddForm({ onSave, onClose }) {
}; };
return ( return (
<Form onSubmit={handleSubmit} error={error}> <Form onSubmit={handleSubmit} error={getErrorMessage(error)}>
<FormField <FormField
label={formatMessage(labels.username)} label={formatMessage(labels.username)}
name="username" name="username"

View file

@ -29,7 +29,7 @@ export function UserEditForm({ userId, onSave }: { userId: string; onSave?: () =
}; };
return ( return (
<Form onSubmit={handleSubmit} error={getMessage(error)} values={user}> <Form onSubmit={handleSubmit} error={getMessage(error?.['code'])} values={user}>
<FormField name="username" label={formatMessage(labels.username)}> <FormField name="username" label={formatMessage(labels.username)}>
<TextField data-test="input-username" /> <TextField data-test="input-username" />
</FormField> </FormField>
@ -37,7 +37,7 @@ export function UserEditForm({ userId, onSave }: { userId: string; onSave?: () =
name="password" name="password"
label={formatMessage(labels.password)} label={formatMessage(labels.password)}
rules={{ rules={{
minLength: { value: 8, message: formatMessage(messages.minPasswordLength, { n: 8 }) }, minLength: { value: 8, message: formatMessage(messages.minPasswordLength, { n: '8' }) },
}} }}
> >
<PasswordField autoComplete="new-password" data-test="input-password" /> <PasswordField autoComplete="new-password" data-test="input-password" />

View file

@ -15,7 +15,7 @@ export function LinkDeleteButton({
name: string; name: string;
onSave?: () => void; onSave?: () => void;
}) { }) {
const { formatMessage, labels } = useMessages(); const { formatMessage, labels, getErrorMessage } = useMessages();
const { mutate, isPending, error, touch } = useDeleteQuery(`/links/${linkId}`); const { mutate, isPending, error, touch } = useDeleteQuery(`/links/${linkId}`);
const handleConfirm = (close: () => void) => { const handleConfirm = (close: () => void) => {
@ -37,7 +37,7 @@ export function LinkDeleteButton({
target: name, target: name,
})} })}
isLoading={isPending} isLoading={isPending}
error={error} error={getErrorMessage(error)}
onConfirm={handleConfirm.bind(null, close)} onConfirm={handleConfirm.bind(null, close)}
onClose={close} onClose={close}
buttonLabel={formatMessage(labels.delete)} buttonLabel={formatMessage(labels.delete)}

View file

@ -32,7 +32,7 @@ export function LinkEditForm({
onSave?: () => void; onSave?: () => void;
onClose?: () => void; onClose?: () => void;
}) { }) {
const { formatMessage, labels, messages } = useMessages(); const { formatMessage, labels, messages, getErrorMessage } = useMessages();
const { mutate, error, isPending, touch, toast } = useUpdateQuery( const { mutate, error, isPending, touch, toast } = useUpdateQuery(
linkId ? `/links/${linkId}` : '/links', linkId ? `/links/${linkId}` : '/links',
{ {
@ -82,7 +82,7 @@ export function LinkEditForm({
} }
return ( return (
<Form onSubmit={handleSubmit} error={error?.message} defaultValues={{ slug, ...data }}> <Form onSubmit={handleSubmit} error={getErrorMessage(error)} defaultValues={{ slug, ...data }}>
{({ setValue }) => { {({ setValue }) => {
return ( return (
<> <>

View file

@ -13,7 +13,7 @@ export function PixelDeleteButton({
name: string; name: string;
onSave?: () => void; onSave?: () => void;
}) { }) {
const { formatMessage, labels } = useMessages(); const { formatMessage, labels, getErrorMessage } = useMessages();
const { mutate, isPending, error } = useDeleteQuery(`/pixels/${pixelId}`); const { mutate, isPending, error } = useDeleteQuery(`/pixels/${pixelId}`);
const { touch } = useModified(); const { touch } = useModified();
@ -36,7 +36,7 @@ export function PixelDeleteButton({
target: name, target: name,
})} })}
isLoading={isPending} isLoading={isPending}
error={error} error={getErrorMessage(error)}
onConfirm={handleConfirm.bind(null, close)} onConfirm={handleConfirm.bind(null, close)}
onClose={close} onClose={close}
buttonLabel={formatMessage(labels.delete)} buttonLabel={formatMessage(labels.delete)}

View file

@ -31,7 +31,7 @@ export function PixelEditForm({
onSave?: () => void; onSave?: () => void;
onClose?: () => void; onClose?: () => void;
}) { }) {
const { formatMessage, labels, messages } = useMessages(); const { formatMessage, labels, messages, getErrorMessage } = useMessages();
const { mutate, error, isPending, touch, toast } = useUpdateQuery( const { mutate, error, isPending, touch, toast } = useUpdateQuery(
pixelId ? `/pixels/${pixelId}` : '/pixels', pixelId ? `/pixels/${pixelId}` : '/pixels',
{ {
@ -74,7 +74,7 @@ export function PixelEditForm({
} }
return ( return (
<Form onSubmit={handleSubmit} error={error?.message} defaultValues={{ slug, ...data }}> <Form onSubmit={handleSubmit} error={getErrorMessage(error)} defaultValues={{ slug, ...data }}>
{({ setValue }) => { {({ setValue }) => {
return ( return (
<> <>

View file

@ -9,7 +9,7 @@ import {
import { useMessages, useUpdateQuery } from '@/components/hooks'; import { useMessages, useUpdateQuery } from '@/components/hooks';
export function PasswordEditForm({ onSave, onClose }) { export function PasswordEditForm({ onSave, onClose }) {
const { formatMessage, labels, messages } = useMessages(); const { formatMessage, labels, messages, getErrorMessage } = useMessages();
const { mutate, error, isPending } = useUpdateQuery('/me/password'); const { mutate, error, isPending } = useUpdateQuery('/me/password');
const handleSubmit = async (data: any) => { const handleSubmit = async (data: any) => {
@ -29,7 +29,7 @@ export function PasswordEditForm({ onSave, onClose }) {
}; };
return ( return (
<Form onSubmit={handleSubmit} error={error}> <Form onSubmit={handleSubmit} error={getErrorMessage(error)}>
<FormField <FormField
label={formatMessage(labels.currentPassword)} label={formatMessage(labels.currentPassword)}
name="currentPassword" name="currentPassword"
@ -42,7 +42,7 @@ export function PasswordEditForm({ onSave, onClose }) {
label={formatMessage(labels.newPassword)} label={formatMessage(labels.newPassword)}
rules={{ rules={{
required: 'Required', required: 'Required',
minLength: { value: 8, message: formatMessage(messages.minPasswordLength, { n: 8 }) }, minLength: { value: 8, message: formatMessage(messages.minPasswordLength, { n: '8' }) },
}} }}
> >
<PasswordField autoComplete="new-password" /> <PasswordField autoComplete="new-password" />
@ -52,7 +52,7 @@ export function PasswordEditForm({ onSave, onClose }) {
label={formatMessage(labels.confirmPassword)} label={formatMessage(labels.confirmPassword)}
rules={{ rules={{
required: formatMessage(labels.required), required: formatMessage(labels.required),
minLength: { value: 8, message: formatMessage(messages.minPasswordLength, { n: 8 }) }, minLength: { value: 8, message: formatMessage(messages.minPasswordLength, { n: '8' }) },
validate: samePassword, validate: samePassword,
}} }}
> >

View file

@ -9,7 +9,7 @@ import {
} from '@umami/react-zen'; } from '@umami/react-zen';
export function TeamAddForm({ onSave, onClose }: { onSave: () => void; onClose: () => void }) { export function TeamAddForm({ onSave, onClose }: { onSave: () => void; onClose: () => void }) {
const { formatMessage, labels } = useMessages(); const { formatMessage, labels, getErrorMessage } = useMessages();
const { mutate, error, isPending } = useUpdateQuery('/teams'); const { mutate, error, isPending } = useUpdateQuery('/teams');
const handleSubmit = async (data: any) => { const handleSubmit = async (data: any) => {
@ -22,7 +22,7 @@ export function TeamAddForm({ onSave, onClose }: { onSave: () => void; onClose:
}; };
return ( return (
<Form onSubmit={handleSubmit} error={error}> <Form onSubmit={handleSubmit} error={getErrorMessage(error)}>
<FormField name="name" label={formatMessage(labels.name)}> <FormField name="name" label={formatMessage(labels.name)}>
<TextField autoComplete="off" /> <TextField autoComplete="off" />
</FormField> </FormField>

View file

@ -9,7 +9,7 @@ import {
import { useMessages, useModified, useUpdateQuery } from '@/components/hooks'; import { useMessages, useModified, useUpdateQuery } from '@/components/hooks';
export function TeamJoinForm({ onSave, onClose }: { onSave: () => void; onClose: () => void }) { export function TeamJoinForm({ onSave, onClose }: { onSave: () => void; onClose: () => void }) {
const { formatMessage, labels } = useMessages(); const { formatMessage, labels, getErrorMessage } = useMessages();
const { mutate, error } = useUpdateQuery('/teams/join'); const { mutate, error } = useUpdateQuery('/teams/join');
const { touch } = useModified(); const { touch } = useModified();
@ -24,7 +24,7 @@ export function TeamJoinForm({ onSave, onClose }: { onSave: () => void; onClose:
}; };
return ( return (
<Form onSubmit={handleSubmit} error={error}> <Form onSubmit={handleSubmit} error={getErrorMessage(error)}>
<FormField <FormField
label={formatMessage(labels.accessCode)} label={formatMessage(labels.accessCode)}
name="accessCode" name="accessCode"

View file

@ -14,7 +14,7 @@ export function TeamLeaveForm({
onSave: () => void; onSave: () => void;
onClose: () => void; onClose: () => void;
}) { }) {
const { formatMessage, labels, messages } = useMessages(); const { formatMessage, labels, messages, getErrorMessage } = useMessages();
const { mutate, error, isPending } = useDeleteQuery(`/teams/${teamId}/users/${userId}`); const { mutate, error, isPending } = useDeleteQuery(`/teams/${teamId}/users/${userId}`);
const { touch } = useModified(); const { touch } = useModified();
@ -37,7 +37,7 @@ export function TeamLeaveForm({
onConfirm={handleConfirm} onConfirm={handleConfirm}
onClose={onClose} onClose={onClose}
isLoading={isPending} isLoading={isPending}
error={error} error={getErrorMessage(error)}
/> />
); );
} }

View file

@ -12,7 +12,7 @@ export function TeamDeleteForm({
onSave?: () => void; onSave?: () => void;
onClose?: () => void; onClose?: () => void;
}) { }) {
const { labels, formatMessage } = useMessages(); const { labels, formatMessage, getErrorMessage } = useMessages();
const { mutate, error, isPending, touch } = useDeleteQuery(`/teams/${teamId}`); const { mutate, error, isPending, touch } = useDeleteQuery(`/teams/${teamId}`);
const handleConfirm = async () => { const handleConfirm = async () => {
@ -31,7 +31,7 @@ export function TeamDeleteForm({
onConfirm={handleConfirm} onConfirm={handleConfirm}
onClose={onClose} onClose={onClose}
isLoading={isPending} isLoading={isPending}
error={error} error={getErrorMessage(error)}
buttonLabel={formatMessage(labels.delete)} buttonLabel={formatMessage(labels.delete)}
buttonVariant="danger" buttonVariant="danger"
/> />

View file

@ -21,7 +21,7 @@ export function TeamEditForm({
onSave?: () => void; onSave?: () => void;
}) { }) {
const team = useTeam(); const team = useTeam();
const { formatMessage, labels, messages } = useMessages(); const { formatMessage, labels, messages, getErrorMessage } = useMessages();
const { mutate, error, isPending, touch, toast } = useUpdateQuery(`/teams/${teamId}`); const { mutate, error, isPending, touch, toast } = useUpdateQuery(`/teams/${teamId}`);
@ -37,7 +37,7 @@ export function TeamEditForm({
}; };
return ( return (
<Form onSubmit={handleSubmit} error={error} defaultValues={{ ...team }}> <Form onSubmit={handleSubmit} error={getErrorMessage(error)} defaultValues={{ ...team }}>
{({ setValue }) => { {({ setValue }) => {
return ( return (
<> <>

View file

@ -24,7 +24,7 @@ export function TeamMemberEditForm({
onClose?: () => void; onClose?: () => void;
}) { }) {
const { mutate, error, isPending } = useUpdateQuery(`/teams/${teamId}/users/${userId}`); const { mutate, error, isPending } = useUpdateQuery(`/teams/${teamId}/users/${userId}`);
const { formatMessage, labels } = useMessages(); const { formatMessage, labels, getErrorMessage } = useMessages();
const handleSubmit = async (data: any) => { const handleSubmit = async (data: any) => {
mutate(data, { mutate(data, {
@ -36,7 +36,7 @@ export function TeamMemberEditForm({
}; };
return ( return (
<Form onSubmit={handleSubmit} error={error} defaultValues={{ role }}> <Form onSubmit={handleSubmit} error={getErrorMessage(error)} defaultValues={{ role }}>
<FormField <FormField
name="role" name="role"
rules={{ required: formatMessage(labels.required) }} rules={{ required: formatMessage(labels.required) }}

View file

@ -13,7 +13,7 @@ export function WebsiteMetricsBar({
compareMode?: boolean; compareMode?: boolean;
}) { }) {
const { dateRange } = useDateRange(websiteId); const { dateRange } = useDateRange(websiteId);
const { formatMessage, labels } = useMessages(); const { formatMessage, labels, getErrorMessage } = useMessages();
const { data, isLoading, isFetching, error } = useWebsiteStatsQuery(websiteId); const { data, isLoading, isFetching, error } = useWebsiteStatsQuery(websiteId);
const isAllTime = dateRange.value === 'all'; const isAllTime = dateRange.value === 'all';
@ -65,7 +65,7 @@ export function WebsiteMetricsBar({
data={metrics} data={metrics}
isLoading={isLoading} isLoading={isLoading}
isFetching={isFetching} isFetching={isFetching}
error={error} error={getErrorMessage(error)}
minHeight="136px" minHeight="136px"
> >
<MetricsBar> <MetricsBar>

View file

@ -31,7 +31,7 @@ export function CohortEditForm({
onClose?: () => void; onClose?: () => void;
}) { }) {
const { data } = useWebsiteCohortQuery(websiteId, cohortId); const { data } = useWebsiteCohortQuery(websiteId, cohortId);
const { formatMessage, labels, messages } = useMessages(); const { formatMessage, labels, messages, getErrorMessage } = useMessages();
const { mutate, error, isPending, touch, toast } = useUpdateQuery( const { mutate, error, isPending, touch, toast } = useUpdateQuery(
`/websites/${websiteId}/segments${cohortId ? `/${cohortId}` : ''}`, `/websites/${websiteId}/segments${cohortId ? `/${cohortId}` : ''}`,
@ -60,7 +60,11 @@ export function CohortEditForm({
}; };
return ( return (
<Form error={error} onSubmit={handleSubmit} defaultValues={data || defaultValues}> <Form
error={getErrorMessage(error)}
onSubmit={handleSubmit}
defaultValues={data || defaultValues}
>
{({ watch }) => { {({ watch }) => {
const type = watch('parameters.action.type'); const type = watch('parameters.action.type');

View file

@ -28,7 +28,7 @@ export function SegmentEditForm({
onClose?: () => void; onClose?: () => void;
}) { }) {
const { data } = useWebsiteSegmentQuery(websiteId, segmentId); const { data } = useWebsiteSegmentQuery(websiteId, segmentId);
const { formatMessage, labels } = useMessages(); const { formatMessage, labels, getErrorMessage } = useMessages();
const { mutate, error, isPending, touch, toast } = useUpdateQuery( const { mutate, error, isPending, touch, toast } = useUpdateQuery(
`/websites/${websiteId}/segments${segmentId ? `/${segmentId}` : ''}`, `/websites/${websiteId}/segments${segmentId ? `/${segmentId}` : ''}`,
@ -53,7 +53,11 @@ export function SegmentEditForm({
} }
return ( return (
<Form error={error} onSubmit={handleSubmit} defaultValues={data || { parameters: { filters } }}> <Form
onSubmit={handleSubmit}
defaultValues={data || { parameters: { filters } }}
error={getErrorMessage(error)}
>
<FormField <FormField
name="name" name="name"
label={formatMessage(labels.name)} label={formatMessage(labels.name)}

View file

@ -4,7 +4,7 @@ import { DOMAIN_REGEX } from '@/lib/constants';
export function WebsiteEditForm({ websiteId, onSave }: { websiteId: string; onSave?: () => void }) { export function WebsiteEditForm({ websiteId, onSave }: { websiteId: string; onSave?: () => void }) {
const website = useWebsite(); const website = useWebsite();
const { formatMessage, labels, messages } = useMessages(); const { formatMessage, labels, messages, getErrorMessage } = useMessages();
const { mutate, error, touch, toast } = useUpdateQuery(`/websites/${websiteId}`); const { mutate, error, touch, toast } = useUpdateQuery(`/websites/${websiteId}`);
const handleSubmit = async (data: any) => { const handleSubmit = async (data: any) => {
@ -18,7 +18,7 @@ export function WebsiteEditForm({ websiteId, onSave }: { websiteId: string; onSa
}; };
return ( return (
<Form onSubmit={handleSubmit} error={error} values={website}> <Form onSubmit={handleSubmit} error={getErrorMessage(error)} values={website}>
<FormField name="id" label={formatMessage(labels.websiteId)}> <FormField name="id" label={formatMessage(labels.websiteId)}>
<TextField data-test="text-field-websiteId" value={website?.id} isReadOnly allowCopy /> <TextField data-test="text-field-websiteId" value={website?.id} isReadOnly allowCopy />
</FormField> </FormField>

View file

@ -23,7 +23,7 @@ export interface WebsiteShareFormProps {
} }
export function WebsiteShareForm({ websiteId, shareId, onSave, onClose }: WebsiteShareFormProps) { export function WebsiteShareForm({ websiteId, shareId, onSave, onClose }: WebsiteShareFormProps) {
const { formatMessage, labels, messages } = useMessages(); const { formatMessage, labels, messages, getErrorMessage } = useMessages();
const [id, setId] = useState(shareId); const [id, setId] = useState(shareId);
const { mutate, error, isPending, touch, toast } = useUpdateQuery(`/websites/${websiteId}`); const { mutate, error, isPending, touch, toast } = useUpdateQuery(`/websites/${websiteId}`);
@ -52,7 +52,7 @@ export function WebsiteShareForm({ websiteId, shareId, onSave, onClose }: Websit
}; };
return ( return (
<Form onSubmit={handleSave} error={error} values={{ url }}> <Form onSubmit={handleSave} error={getErrorMessage(error)} values={{ url }}>
<Column gap> <Column gap>
<Switch isSelected={!!id} onChange={handleSwitch}> <Switch isSelected={!!id} onChange={handleSwitch}>
{formatMessage(labels.enableShareUrl)} {formatMessage(labels.enableShareUrl)}

View file

@ -31,7 +31,7 @@ export function WebsiteTransferForm({
const { user } = useLoginQuery(); const { user } = useLoginQuery();
const website = useWebsite(); const website = useWebsite();
const [teamId, setTeamId] = useState<string>(null); const [teamId, setTeamId] = useState<string>(null);
const { formatMessage, labels, messages } = useMessages(); const { formatMessage, labels, messages, getErrorMessage } = useMessages();
const { mutate, error, isPending } = useUpdateQuery(`/websites/${websiteId}/transfer`); const { mutate, error, isPending } = useUpdateQuery(`/websites/${websiteId}/transfer`);
const { data: teams, isLoading } = useUserTeamsQuery(user.id); const { data: teams, isLoading } = useUserTeamsQuery(user.id);
const isTeamWebsite = !!website?.teamId; const isTeamWebsite = !!website?.teamId;
@ -68,7 +68,7 @@ export function WebsiteTransferForm({
} }
return ( return (
<Form onSubmit={handleSubmit} error={error} values={{ teamId }}> <Form onSubmit={handleSubmit} error={getErrorMessage(error)} values={{ teamId }}>
<Text> <Text>
{formatMessage( {formatMessage(
isTeamWebsite ? messages.transferTeamWebsiteToUser : messages.transferUserWebsiteToTeam, isTeamWebsite ? messages.transferTeamWebsiteToUser : messages.transferUserWebsiteToTeam,

View file

@ -4,7 +4,8 @@ import redis from '@/lib/redis';
import { getUserByUsername } from '@/queries'; import { getUserByUsername } from '@/queries';
import { json, unauthorized } from '@/lib/response'; import { json, unauthorized } from '@/lib/response';
import { parseRequest } from '@/lib/request'; import { parseRequest } from '@/lib/request';
import { saveAuth, checkPassword } from '@/lib/auth'; import { saveAuth } from '@/lib/auth';
import { checkPassword } from '@/lib/password';
import { secret } from '@/lib/crypto'; import { secret } from '@/lib/crypto';
import { ROLES } from '@/lib/constants'; import { ROLES } from '@/lib/constants';

View file

@ -16,7 +16,7 @@ import { setClientAuthToken } from '@/lib/client';
import { Logo } from '@/components/icons'; import { Logo } from '@/components/icons';
export function LoginForm() { export function LoginForm() {
const { formatMessage, labels } = useMessages(); const { formatMessage, labels, getErrorMessage } = useMessages();
const router = useRouter(); const router = useRouter();
const { mutate, error, isPending } = useUpdateQuery('/auth/login'); const { mutate, error, isPending } = useUpdateQuery('/auth/login');
@ -32,12 +32,12 @@ export function LoginForm() {
}; };
return ( return (
<Column justifyContent="center" alignItems="center" padding="8" gap="6"> <Column justifyContent="center" alignItems="center" gap="6">
<Icon size="lg"> <Icon size="lg">
<Logo /> <Logo />
</Icon> </Icon>
<Heading>umami</Heading> <Heading>umami</Heading>
<Form onSubmit={handleSubmit} error={error}> <Form onSubmit={handleSubmit} error={getErrorMessage(error)}>
<FormField <FormField
label={formatMessage(labels.username)} label={formatMessage(labels.username)}
data-test="input-username" data-test="input-username"
@ -58,6 +58,7 @@ export function LoginForm() {
<FormSubmitButton <FormSubmitButton
data-test="button-submit" data-test="button-submit"
variant="primary" variant="primary"
isLoading={isPending}
isDisabled={isPending} isDisabled={isPending}
style={{ flex: 1 }} style={{ flex: 1 }}
> >

View file

@ -4,7 +4,7 @@ import { LoginForm } from './LoginForm';
export function LoginPage() { export function LoginPage() {
return ( return (
<Column justifyContent="center" alignItems="center" height="100vh" backgroundColor="2"> <Column alignItems="center" height="100vh" backgroundColor="2" paddingTop="12">
<LoginForm /> <LoginForm />
</Column> </Column>
); );

View file

@ -21,10 +21,10 @@ export function ConfirmationForm({
onConfirm, onConfirm,
onClose, onClose,
}: ConfirmationFormProps) { }: ConfirmationFormProps) {
const { formatMessage, labels } = useMessages(); const { formatMessage, labels, getErrorMessage } = useMessages();
return ( return (
<Form onSubmit={onConfirm} error={error}> <Form onSubmit={onConfirm} error={getErrorMessage(error)}>
<Row marginY="4">{message}</Row> <Row marginY="4">{message}</Row>
<FormButtons> <FormButtons>
<Button onPress={onClose}>{formatMessage(labels.cancel)}</Button> <Button onPress={onClose}>{formatMessage(labels.cancel)}</Button>

View file

@ -5,7 +5,7 @@ import { Empty } from '@/components/common/Empty';
export interface LoadingPanelProps extends ColumnProps { export interface LoadingPanelProps extends ColumnProps {
data?: any; data?: any;
error?: Error; error?: unknown;
isEmpty?: boolean; isEmpty?: boolean;
isLoading?: boolean; isLoading?: boolean;
isFetching?: boolean; isFetching?: boolean;

View file

@ -25,14 +25,13 @@ export function TypeConfirmationForm({
onConfirm?: () => void; onConfirm?: () => void;
onClose?: () => void; onClose?: () => void;
}) { }) {
const { formatMessage, labels, messages } = useMessages(); const { formatMessage, labels, messages, getErrorMessage } = useMessages();
if (!confirmationValue) { if (!confirmationValue) {
return null; return null;
} }
return ( return (
<Form onSubmit={onConfirm} error={error}> <Form onSubmit={onConfirm} error={getErrorMessage(error)}>
<p> <p>
{formatMessage(messages.actionConfirmation, { {formatMessage(messages.actionConfirmation, {
confirmation: confirmationValue, confirmation: confirmationValue,

View file

@ -1,6 +1,6 @@
import { useToast } from '@umami/react-zen';
import { useApi } from '../useApi'; import { useApi } from '../useApi';
import { useModified } from '../useModified'; import { useModified } from '../useModified';
import { useToast } from '@umami/react-zen';
export function useUpdateQuery(path: string, params?: Record<string, any>) { export function useUpdateQuery(path: string, params?: Record<string, any>) {
const { post, useMutation } = useApi(); const { post, useMutation } = useApi();

View file

@ -2,23 +2,18 @@ import { useCallback } from 'react';
import { useQuery, useMutation } from '@tanstack/react-query'; import { useQuery, useMutation } from '@tanstack/react-query';
import { getClientAuthToken } from '@/lib/client'; import { getClientAuthToken } from '@/lib/client';
import { SHARE_TOKEN_HEADER } from '@/lib/constants'; import { SHARE_TOKEN_HEADER } from '@/lib/constants';
import { httpGet, httpPost, httpPut, httpDelete, FetchResponse } from '@/lib/fetch'; import { httpGet, httpPost, httpPut, httpDelete, FetchResponse, ErrorResponse } from '@/lib/fetch';
import { useApp } from '@/store/app'; import { useApp } from '@/store/app';
const selector = (state: { shareToken: { token?: string } }) => state.shareToken; const selector = (state: { shareToken: { token?: string } }) => state.shareToken;
async function handleResponse(res: FetchResponse): Promise<any> { async function handleResponse(res: FetchResponse): Promise<any> {
if (res.error) { if (!res.ok) {
const { message, code } = res?.error?.error || {}; return Promise.reject(res.data?.error as ErrorResponse);
return Promise.reject(new Error(code || message || 'Unexpected error.'));
} }
return Promise.resolve(res.data); return Promise.resolve(res.data);
} }
function handleError(err: Error | string) {
return Promise.reject((err as Error)?.message || err || null);
}
export function useApi() { export function useApi() {
const shareToken = useApp(selector); const shareToken = useApp(selector);
@ -39,36 +34,28 @@ export function useApi() {
return { return {
get: useCallback( get: useCallback(
async (url: string, params: object = {}, headers: object = {}) => { async (url: string, params: object = {}, headers: object = {}) => {
return httpGet(getUrl(url), params, getHeaders(headers)) return httpGet(getUrl(url), params, getHeaders(headers)).then(handleResponse);
.then(handleResponse)
.catch(handleError);
}, },
[httpGet], [httpGet],
), ),
post: useCallback( post: useCallback(
async (url: string, params: object = {}, headers: object = {}) => { async (url: string, params: object = {}, headers: object = {}) => {
return httpPost(getUrl(url), params, getHeaders(headers)) return httpPost(getUrl(url), params, getHeaders(headers)).then(handleResponse);
.then(handleResponse)
.catch(handleError);
}, },
[httpPost], [httpPost],
), ),
put: useCallback( put: useCallback(
async (url: string, params: object = {}, headers: object = {}) => { async (url: string, params: object = {}, headers: object = {}) => {
return httpPut(getUrl(url), params, getHeaders(headers)) return httpPut(getUrl(url), params, getHeaders(headers)).then(handleResponse);
.then(handleResponse)
.catch(handleError);
}, },
[httpPut], [httpPut],
), ),
del: useCallback( del: useCallback(
async (url: string, params: object = {}, headers: object = {}) => { async (url: string, params: object = {}, headers: object = {}) => {
return httpDelete(getUrl(url), params, getHeaders(headers)) return httpDelete(getUrl(url), params, getHeaders(headers)).then(handleResponse);
.then(handleResponse)
.catch(handleError);
}, },
[httpDelete], [httpDelete],
), ),

View file

@ -10,6 +10,16 @@ export function useMessages() {
return message ? formatMessage(message) : id; return message ? formatMessage(message) : id;
}; };
const getErrorMessage = (error: unknown) => {
if (!error) {
return undefined;
}
const code = error?.['code'];
return code ? getMessage(code) : error?.['message'] || 'Unknown error';
};
const formatMessage = ( const formatMessage = (
descriptor: { descriptor: {
id: string; id: string;
@ -21,5 +31,5 @@ export function useMessages() {
return descriptor ? intl.formatMessage(descriptor, values, opts) : null; return descriptor ? intl.formatMessage(descriptor, values, opts) : null;
}; };
return { formatMessage, messages, labels, getMessage }; return { formatMessage, messages, labels, getMessage, getErrorMessage };
} }

View file

@ -1,6 +1,6 @@
import { useState, useEffect } from 'react'; import { useState, useEffect } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation'; import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { buildUrl } from '@/lib/url'; import { buildPath } from '@/lib/url';
export function useNavigation() { export function useNavigation() {
const router = useRouter(); const router = useRouter();
@ -11,15 +11,15 @@ export function useNavigation() {
const [queryParams, setQueryParams] = useState(Object.fromEntries(searchParams)); const [queryParams, setQueryParams] = useState(Object.fromEntries(searchParams));
const updateParams = (params?: Record<string, string | number>) => { const updateParams = (params?: Record<string, string | number>) => {
return buildUrl(pathname, { ...queryParams, ...params }); return buildPath(pathname, { ...queryParams, ...params });
}; };
const replaceParams = (params?: Record<string, string | number>) => { const replaceParams = (params?: Record<string, string | number>) => {
return buildUrl(pathname, params); return buildPath(pathname, params);
}; };
const renderUrl = (path: string, params?: Record<string, string | number> | false) => { const renderUrl = (path: string, params?: Record<string, string | number> | false) => {
return buildUrl( return buildPath(
teamId ? `/teams/${teamId}${path}` : path, teamId ? `/teams/${teamId}${path}` : path,
params === false ? {} : { ...queryParams, ...params }, params === false ? {} : { ...queryParams, ...params },
); );

View file

@ -1,4 +1,4 @@
import { buildUrl } from '@/lib/url'; import { buildPath } from '@/lib/url';
export interface ErrorResponse { export interface ErrorResponse {
error: { error: {
@ -36,18 +36,17 @@ export async function request(
return { return {
ok: res.ok, ok: res.ok,
status: res.status, status: res.status,
data: res.ok ? data : undefined, data,
error: res.ok ? undefined : data,
}; };
}); });
} }
export async function httpGet(path: string, params: object = {}, headers: object = {}) { export async function httpGet(path: string, params: object = {}, headers: object = {}) {
return request('GET', buildUrl(path, params), undefined, headers); return request('GET', buildPath(path, params), undefined, headers);
} }
export async function httpDelete(path: string, params: object = {}, headers: object = {}) { export async function httpDelete(path: string, params: object = {}, headers: object = {}) {
return request('DELETE', buildUrl(path, params), undefined, headers); return request('DELETE', buildPath(path, params), undefined, headers);
} }
export async function httpPost(path: string, params: object = {}, headers: object = {}) { export async function httpPost(path: string, params: object = {}, headers: object = {}) {

View file

@ -10,9 +10,9 @@ export function getQueryString(params: object = {}): string {
return searchParams.toString(); return searchParams.toString();
} }
export function buildUrl(url: string, params: object = {}): string { export function buildPath(path: string, params: object = {}): string {
const queryString = getQueryString(params); const queryString = getQueryString(params);
return `${url}${queryString && '?' + queryString}`; return queryString ? `${path}?${queryString}` : path;
} }
export function safeDecodeURI(s: string | undefined | null): string | undefined | null { export function safeDecodeURI(s: string | undefined | null): string | undefined | null {