/* eslint-disable @typescript-eslint/no-unnecessary-condition */ import * as Solid from 'solid-js' import { render } from 'solid-js/web' import { ErrorComponent, Link, MatchRoute, Outlet, RouterProvider, createRootRouteWithContext, createRoute, createRouter, lazyRouteComponent, redirect, retainSearchParams, useNavigate, useRouter, useRouterState, useSearch, } from '@tanstack/solid-router' import { TanStackRouterDevtools } from '@tanstack/solid-router-devtools' import { QueryClient, QueryClientProvider, queryOptions, useMutation, useQuery, } from '@tanstack/solid-query' import { SolidQueryDevtools } from '@tanstack/solid-query-devtools' import { z } from 'zod' import { fetchInvoiceById, fetchInvoices, fetchUserById, fetchUsers, patchInvoice, postInvoice, } from './mockTodos' import type { Invoice } from './mockTodos' import './styles.css' // type UsersViewSortBy = 'name' | 'id' | 'email' const invoicesQueryOptions = () => queryOptions({ queryKey: ['invoices'], queryFn: () => fetchInvoices(), }) const invoiceQueryOptions = (invoiceId: number) => queryOptions({ queryKey: ['invoices', invoiceId], queryFn: () => fetchInvoiceById(invoiceId), }) const usersQueryOptions = ({ filterBy, sortBy, }: { filterBy?: string sortBy?: UsersViewSortBy }) => queryOptions({ queryKey: ['users', { filterBy, sortBy }], queryFn: () => fetchUsers({ filterBy, sortBy, }), }) const userQueryOptions = (userId: number) => queryOptions({ queryKey: ['users', userId], queryFn: async () => { const user = await fetchUserById(userId) if (!user) { throw new Error('User not found.') } return user }, }) const useCreateInvoiceMutation = () => { return useMutation(() => ({ mutationKey: ['invoices', 'create'], mutationFn: postInvoice, onSuccess: () => queryClient.invalidateQueries(), })) } const useUpdateInvoiceMutation = (invoiceId: number) => { return useMutation(() => ({ mutationKey: ['invoices', 'update', invoiceId], mutationFn: patchInvoice, onSuccess: () => queryClient.invalidateQueries(), gcTime: 1000 * 10, })) } function RouterSpinner() { const isLoading = useRouterState({ select: (s) => s.status === 'pending' }) return } // Routes // Build our routes. We could do this in our component, too. const rootRoute = createRootRouteWithContext<{ auth: Auth queryClient: QueryClient }>()({ component: RootComponent, }) function RootComponent() { return ( <>

Kitchen Sink

{/* Show a global spinner when the router is transitioning */}
{( [ ['/', 'Home'], ['/dashboard', 'Dashboard'], ['/expensive', 'Expensive'], ['/route-a', 'Pathless Layout A'], ['/route-b', 'Pathless Layout B'], ['/profile', 'Profile'], ['/login', 'Login'], ] as const ).map(([to, label]) => { return (
{label}
) })}
{/* Render our first route match */}
) } const indexRoute = createRoute({ getParentRoute: () => rootRoute, path: '/', component: IndexComponent, }) function IndexComponent() { return (
Welcome Home!

1 New Invoice
As you navigate around take note of the UX. It should feel suspense-like, where routes are only rendered once all of their data and elements are ready.
To exaggerate async effects, play with the artificial request delay slider in the bottom-left corner.
The last 2 sliders determine if link-hover preloading is enabled (and how long those preloads stick around) and also whether to cache rendered route data (and for how long). Both of these default to 0 (or off).
) } const dashboardLayoutRoute = createRoute({ getParentRoute: () => rootRoute, path: 'dashboard', component: DashboardLayoutComponent, }) function DashboardLayoutComponent() { return ( <>

Dashboard

{( [ ['/dashboard', 'Summary', true], ['/dashboard/invoices', 'Invoices'], ['/dashboard/users', 'Users'], ] as const ).map(([to, label, exact]) => { return ( {label} ) })}

) } const dashboardIndexRoute = createRoute({ getParentRoute: () => dashboardLayoutRoute, path: '/', loader: (opts) => opts.context.queryClient.ensureQueryData(invoicesQueryOptions()), component: DashboardIndexComponent, }) function DashboardIndexComponent() { const invoicesQuery = useQuery(() => invoicesQueryOptions()) const invoices = invoicesQuery.data return (
Welcome to the dashboard! You have{' '} {invoices?.length} total invoices.
) } const invoicesLayoutRoute = createRoute({ getParentRoute: () => dashboardLayoutRoute, path: 'invoices', loader: (opts) => opts.context.queryClient.ensureQueryData(invoicesQueryOptions()), component: InvoicesLayoutComponent, }) function InvoicesLayoutComponent() { const invoicesQuery = useQuery(() => invoicesQueryOptions()) const invoices = invoicesQuery.data // const updateInvoiceMutation = useUpdateInvoiceMutation() // const createInvoiceMutation = useCreateInvoiceMutation() return (
{/* {routerTransitionIsPending ? 'pending' : 'null'} */}
{invoices?.map((invoice) => { // const updateSubmission = updateInvoiceMutation.submissions.find( // (d) => d.variables?.id === invoice.id, // ) // if (updateSubmission) { // invoice = { // ...invoice, // ...updateSubmission.variables, // } // } return (
                  #{invoice.id} - {invoice.title.slice(0, 10)}{' '}
                  {/* {updateSubmission ? (
                      
                    ) : ( */}
                  
                    {(match) => }
                  
                  {/* )} */}
                
) })} {/* {createSubmissions.map((action) => ( ))} */}
) } const invoicesIndexRoute = createRoute({ getParentRoute: () => invoicesLayoutRoute, path: '/', component: InvoicesIndexComponent, }) function InvoicesIndexComponent() { const createInvoiceMutation = useCreateInvoiceMutation() return ( <>
{ event.preventDefault() event.stopPropagation() const formData = new FormData(event.target as HTMLFormElement) createInvoiceMutation.mutate({ title: formData.get('title') as string, body: formData.get('body') as string, }) }} class="space-y-2" >
Create a new Invoice:
{createInvoiceMutation.status === 'success' ? (
Created!
) : createInvoiceMutation.status === 'error' ? (
Failed to create.
) : null}
) } const invoiceRoute = createRoute({ getParentRoute: () => invoicesLayoutRoute, path: '$invoiceId', params: { parse: (params) => ({ invoiceId: z.number().int().parse(Number(params.invoiceId)), }), stringify: ({ invoiceId }) => ({ invoiceId: `${invoiceId}` }), }, validateSearch: (search) => z .object({ showNotes: z.boolean().optional(), notes: z.string().optional(), }) .parse(search), loader: (opts) => opts.context.queryClient.ensureQueryData( invoiceQueryOptions(opts.params.invoiceId), ), component: InvoiceComponent, }) function InvoiceComponent() { const params = invoiceRoute.useParams() const search = invoiceRoute.useSearch() const navigate = useNavigate({ from: invoiceRoute.fullPath }) const invoiceQuery = useQuery(() => invoiceQueryOptions(params().invoiceId)) const invoice = invoiceQuery.data const updateInvoiceMutation = useUpdateInvoiceMutation(params().invoiceId) const [notes, setNotes] = Solid.createSignal(search().notes ?? '') Solid.createEffect(() => { navigate({ search: (old: any) => ({ ...old, notes: notes() ? notes() : undefined, }), replace: true, params: true, }) }) return (
{ event.preventDefault() event.stopPropagation() const formData = new FormData(event.target as HTMLFormElement) updateInvoiceMutation.mutate({ id: invoice!.id, title: formData.get('title') as string, body: formData.get('body') as string, }) }} class="p-2 space-y-2" >
({ ...old, showNotes: old.showNotes ? undefined : true, })} class="text-blue-700" from={invoiceRoute.fullPath} params={true} > {search().showNotes ? 'Close Notes' : 'Show Notes'}{' '} {search().showNotes ? ( <>