Skip to content

Black Friday

Annual Pro is $90 for the first year, normally $120. Or start monthly at $6 for two months, then $12.

Ends Dec 4, 11:59 PM PT.

Create an account
← Public packages

@kody/example-habit-log

A small habit log app built from the app starter: indigo theme, mobile layout, sign-in, and saved entries.

FollowFork

Files

items.tsx

139 lines · 3.7 KB · TypeScript
import { createRoute, useRouter } from '@tanstack/react-router'
import { useMutation, useQueryClient, useSuspenseQuery } from '@tanstack/react-query'
import { useForm } from '@tanstack/react-form'
import { site } from '../content/site.ts'
import { authLinks } from '../auth.ts'
import { Alert, Button, EmptyState, LoadingRows, TextField } from '../components/ui.tsx'
import { itemsQuery, type RouterContext } from '../router-context.ts'
import { rootRoute } from './root.tsx'

function ItemsList() {
	const router = useRouter()
	const { api } = router.options.context as RouterContext
	const queryClient = useQueryClient()
	const { data: items } = useSuspenseQuery(itemsQuery(api))
	const refresh = () => queryClient.invalidateQueries({ queryKey: ['items'] })
	const add = useMutation({
		mutationFn: (value: string) => api.addItem(value),
		onSuccess: refresh,
	})
	const remove = useMutation({
		mutationFn: (id: string) => api.deleteItem(id),
		onSettled: refresh,
	})
	const form = useForm({
		defaultValues: { text: '' },
		onSubmit: async ({ value, formApi }) => {
			const text = value.text.trim()
			if (!text) return
			try {
				await add.mutateAsync(text)
				formApi.reset()
			} catch {
				// add.error renders the alert below.
			}
		},
	})
	return (
		<>
			<form
				className="row"
				onSubmit={(event) => {
					event.preventDefault()
					void form.handleSubmit()
				}}
			>
				<form.Field name="text">
					{(field) => (
						<TextField
							label={site.items.addLabel}
							name={field.name}
							value={field.state.value}
							onBlur={field.handleBlur}
							onChange={(event) => field.handleChange(event.target.value)}
							required
							maxLength={200}
						/>
					)}
				</form.Field>
				<form.Subscribe selector={(state) => state.isSubmitting}>
					{(isSubmitting) => (
						<Button type="submit" variant="primary" disabled={isSubmitting}>
							{isSubmitting ? 'Adding…' : site.items.addButton}
						</Button>
					)}
				</form.Subscribe>
			</form>
			{add.error || remove.error ? (
				<Alert title="That did not save">
					<p className="muted">{(add.error ?? remove.error)?.message}</p>
				</Alert>
			) : null}
			{items.length === 0 ? (
				<EmptyState>{site.items.empty}</EmptyState>
			) : (
				<ul className="list" aria-label={site.items.heading}>
					{items.map((item) => (
						<li key={item.id}>
							<span>{item.text}</span>
							<Button
								onClick={() => remove.mutate(item.id)}
								disabled={remove.isPending}
								aria-label={`Delete ${item.text}`}
							>
								Delete
							</Button>
						</li>
					))}
				</ul>
			)}
		</>
	)
}

export const itemsRoute = createRoute({
	getParentRoute: () => rootRoute,
	path: '/items',
	staticData: { title: site.items.heading },
	loader: ({ context }) =>
		context.visitor
			? context.queryClient.ensureQueryData(itemsQuery(context.api))
			: null,
	pendingComponent: () => (
		<section className="card">
			<h1>{site.items.heading}</h1>
			<LoadingRows label="Loading your list" />
		</section>
	),
	component: function Items() {
		const router = useRouter()
		const context = router.options.context as RouterContext
		return (
			<section className="card">
				<h1>{site.items.heading}</h1>
				<p className="muted">{site.items.lede}</p>
				{context.visitor ? (
					<ItemsList />
				) : (
					<>
						<EmptyState>{site.items.signInPrompt}</EmptyState>
						<div>
							<a
								className="button"
								data-variant="primary"
								href={
									authLinks({
										hostedUrl: context.hostedUrl,
										returnTo: `${context.appBasePath}/items`,
									}).signIn
								}
							>
								{site.account.signIn}
							</a>
						</div>
					</>
				)}
			</section>
		)
	},
})