| | | 1 | | import { redirect } from "react-router"; |
| | | 2 | | import type { Route } from "./+types/locations.new"; |
| | | 3 | | import { routes } from "~/constants/routes"; |
| | | 4 | | import { createLocation } from "~/api/client"; |
| | | 5 | | import { LocationForm } from "~/features/locations"; |
| | | 6 | | import { tryApi } from "~/lib/action-helpers.server"; |
| | | 7 | | import { useToastFromActionData } from "~/lib/toasts"; |
| | | 8 | | import { pushFlash } from "~/lib/toasts.server"; |
| | | 9 | | |
| | 0 | 10 | | export async function action({ request }: Route.ActionArgs) { |
| | 0 | 11 | | const formData = await request.formData(); |
| | 0 | 12 | | const name = formData.get("name"); |
| | 0 | 13 | | const description = formData.get("description"); |
| | 0 | 14 | | if (typeof name !== "string" || !name.trim()) { |
| | 0 | 15 | | return { ok: false as const, error: "Name is required" }; |
| | | 16 | | } |
| | 0 | 17 | | const result = await tryApi(() => |
| | | 18 | | createLocation( |
| | | 19 | | { |
| | | 20 | | name: name.trim(), |
| | | 21 | | description: |
| | | 22 | | typeof description === "string" && description.trim() |
| | | 23 | | ? description.trim() |
| | | 24 | | : undefined, |
| | | 25 | | }, |
| | | 26 | | request, |
| | | 27 | | ), |
| | | 28 | | ); |
| | 0 | 29 | | if (!result.ok) return result; |
| | 0 | 30 | | await pushFlash(request, { |
| | | 31 | | kind: "success", |
| | | 32 | | message: `Location "${result.data.name}" created`, |
| | | 33 | | }); |
| | 0 | 34 | | return redirect(routes.locations.list()); |
| | | 35 | | } |
| | | 36 | | |
| | 0 | 37 | | export function meta(_args: Route.MetaArgs) { |
| | 0 | 38 | | return [{ title: "Add location | ClutterStock" }]; |
| | | 39 | | } |
| | | 40 | | |
| | 0 | 41 | | export default function LocationNew({ actionData }: Route.ComponentProps) { |
| | 0 | 42 | | useToastFromActionData(actionData); |
| | | 43 | | const error = |
| | 0 | 44 | | actionData && "error" in actionData ? actionData.error : undefined; |
| | | 45 | | const fieldErrors = |
| | 0 | 46 | | actionData && "fieldErrors" in actionData ? actionData.fieldErrors : undefined; |
| | 0 | 47 | | return ( |
| | | 48 | | <LocationForm |
| | | 49 | | title="Add location" |
| | | 50 | | submitLabel="Create" |
| | | 51 | | error={error} |
| | | 52 | | fieldErrors={fieldErrors} |
| | | 53 | | /> |
| | | 54 | | ); |
| | | 55 | | } |