### Basic Router Setup Source: https://docs.solidjs.com/solid-router/reference/components/router Demonstrates a basic setup of the Solid Router with a root layout component and a home route. This example shows how to integrate the Router with your Solid application's rendering process. ```typescript import { render } from "solid-js/web"; import { Route, Router } from "@solidjs/router"; function Layout(props) { return ( <>

Root header

{props.children} ); } render( () => (

Home

} />
), document.getElementById("root")! ); ``` -------------------------------- ### createAsync Basic Usage Example Source: https://docs.solidjs.com/solid-router/reference/data-apis/create-async A simple example demonstrating how to use createAsync to fetch user data and display it. ```APIDOC ## Examples ### Basic usage ``` import { createAsync, query } from "@solidjs/router"; const getCurrentUser = query(async () => { const response = await fetch("/api/current-user"); return response.json() as Promise<{ name: string }>; }, "currentUser"); function UserProfile() { const user = createAsync(() => getCurrentUser()); return
{user()?.name}
; } ``` ``` -------------------------------- ### createAsync Example with Parameter Source: https://docs.solidjs.com/solid-router/reference/data-apis/create-async An example showing how to use createAsync with a dynamic parameter to fetch invoice details. ```APIDOC ### With parameter ``` import { createAsync, query } from "@solidjs/router"; type Invoice = { number: string; total: number; }; const getInvoice = query(async (invoiceId: string) => { const response = await fetch(`/api/invoices/${invoiceId}`); return response.json() as Promise; }, "invoice"); function InvoiceDetails(props: { invoiceId: string }) { const invoice = createAsync(() => getInvoice(props.invoiceId)); return (

Invoice #{invoice()?.number}

Total: ${invoice()?.total}

); } ``` ``` -------------------------------- ### Basic Usage Example Source: https://docs.solidjs.com/solid-router/reference/primitives/use-is-routing This example demonstrates how to use the `useIsRouting` hook to conditionally display a "Loading route..." message while a route transition is in progress. ```APIDOC ## Examples ### Basic usage ```javascript import { Show } from "solid-js"; import { useIsRouting } from "@solidjs/router"; function PendingRoute() { const isRouting = useIsRouting(); return Loading route...; } ``` ``` -------------------------------- ### createAsyncStore Example Source: https://docs.solidjs.com/solid-router/reference/data-apis/create-async-store Demonstrates how to use createAsyncStore with reactive arguments to fetch and display a list of notifications. ```APIDOC ## Examples ### With reactive arguments ```typescript import { For, createSignal } from "solid-js"; import { createAsyncStore, query } from "@solidjs/router"; type Notification = { id: string; message: string; user: { name: string }; }; const getNotifications = query(async (unreadOnly: boolean) => { const response = await fetch(`/api/notifications?unread=${unreadOnly}`); return response.json() as Promise; }, "notifications"); function Notifications() { const [unreadOnly, setUnreadOnly] = createSignal(false); const notifications = createAsyncStore(() => getNotifications(unreadOnly()), { initialValue: [], }); return ( <> ); } ``` ``` -------------------------------- ### Basic Usage Example Source: https://docs.solidjs.com/solid-router/reference/primitives/use-navigate Demonstrates the basic usage of the useNavigate hook to navigate to a new route. ```APIDOC ## Example: Basic usage ```javascript import { useNavigate } from "@solidjs/router"; const navigate = useNavigate(); navigate("/users/123"); ``` ``` -------------------------------- ### Install Solid Router with bun Source: https://docs.solidjs.com/solid-router/getting-started/installation-and-setup Use this command to install Solid Router if you are using bun as your package manager. ```bash bun i @solidjs/router ``` -------------------------------- ### Install Solid Router with yarn Source: https://docs.solidjs.com/solid-router/getting-started/installation-and-setup Use this command to install Solid Router if you are using yarn as your package manager. ```bash yarn add @solidjs/router ``` -------------------------------- ### Install Solid Router with deno Source: https://docs.solidjs.com/solid-router/getting-started/installation-and-setup Use this command to install Solid Router if you are using deno and want to leverage npm packages. ```bash deno add npm:@solidjs/router ``` -------------------------------- ### Install Solid Router with npm Source: https://docs.solidjs.com/solid-router/getting-started/installation-and-setup Use this command to install Solid Router if you are using npm as your package manager. ```bash npm i @solidjs/router ``` -------------------------------- ### Example: Fetching Notifications with Reactive Arguments Source: https://docs.solidjs.com/solid-router/reference/data-apis/create-async-store This example demonstrates using `createAsyncStore` to fetch a list of notifications. It uses a signal `unreadOnly` to dynamically change the fetch query, and the `notifications` store updates reactively. ```typescript import { For, createSignal } from "solid-js"; import { createAsyncStore, query } from "@solidjs/router"; type Notification = { id: string; message: string; user: { name: string }; }; const getNotifications = query(async (unreadOnly: boolean) => { const response = await fetch(`/api/notifications?unread=${unreadOnly}`); return response.json() as Promise; }, "notifications"); function Notifications() { const [unreadOnly, setUnreadOnly] = createSignal(false); const notifications = createAsyncStore(() => getNotifications(unreadOnly()), { initialValue: [], }); return ( <>
    {(notification) => (
  • {notification.message}
    {notification.user.name}
  • )}
); } ``` -------------------------------- ### Install Solid Router with pnpm Source: https://docs.solidjs.com/solid-router/getting-started/installation-and-setup Use this command to install Solid Router if you are using pnpm as your package manager. ```bash pnpm i @solidjs/router ``` -------------------------------- ### createAsync Example with Suspense and ErrorBoundary Source: https://docs.solidjs.com/solid-router/reference/data-apis/create-async Demonstrates integrating createAsync with SolidJS's Suspense and ErrorBoundary for robust data fetching. ```APIDOC ### With Suspense and ErrorBoundary ``` import { ErrorBoundary, For, Suspense } from "solid-js"; import { createAsync, query } from "@solidjs/router"; type Recipe = { name: string; time: string; }; const getRecipes = query(async () => { const response = await fetch("/api/recipes"); return response.json() as Promise; }, "recipes"); function Recipes() { const recipes = createAsync(() => getRecipes()); return ( Couldn't fetch any recipes.

}> Fetching recipes...

}> {(recipe) => (

{recipe.name}

Cook time: {recipe.time}

)}
); } ``` ``` -------------------------------- ### Prefilled Arguments Example Source: https://docs.solidjs.com/solid-router/reference/data-apis/action Shows how to use the `with` method of an action to create a new action with pre-filled arguments, like a user ID. ```APIDOC ## Prefilled Arguments ### Example ```typescript import { action } from "@solidjs/router"; const addTodo = action(async (userId: string, data: URLSearchParams) => { return { userId, title: data.get("title")?.toString(), }; }, "addTodo"); function TodoForm(props: { userId: string }) { return (
); } ``` ``` -------------------------------- ### Basic Usage Example Source: https://docs.solidjs.com/solid-router/reference/data-apis/query Demonstrates how to use the `query` function to cache an asynchronous data fetching operation and how to generate a cache key. ```APIDOC ## Basic usage ```typescript import { query } from "@solidjs/router"; const getUserProfile = query(async (userId: string) => { const response = await fetch(`/api/users/${encodeURIComponent(userId)}`); const json = await response.json(); if (!response.ok) { throw new Error(json?.message ?? "Failed to load user profile."); } return json as { name: string }; }, "userProfile"); const key = getUserProfile.keyFor("123"); ``` ``` -------------------------------- ### Basic Usage Example Source: https://docs.solidjs.com/solid-router/reference/data-apis/action Demonstrates how to use the `action` function for a basic form submission to add a todo item. ```APIDOC ## Basic Usage ### Example ```typescript import { action } from "@solidjs/router"; const addTodo = action(async (data: URLSearchParams) => { return data.get("title")?.toString(); }, "addTodo"); function TodoForm() { return (
); } ``` ``` -------------------------------- ### Example with Filters Source: https://docs.solidjs.com/solid-router/reference/primitives/use-match Shows how to use useMatch with filters for route parameters, including an array of allowed values for 'lang' and a regex for 'slug'. ```APIDOC ### With filters ```jsx import { useMatch } from "@solidjs/router"; import { Show } from "solid-js"; function BlogPost() { const match = useMatch(() => "/:lang?/blog/:slug", { lang: ["en", "es", "fr"], slug: /^[a-z0-9-]+$/, }); const lang = () => match()?.params.lang || "en"; return (

Blog slug: {match()?.params.slug}

); } ``` ``` -------------------------------- ### Basic Usage Example Source: https://docs.solidjs.com/solid-router/reference/response-helpers/redirect Demonstrates how to use the `redirect` function within a query to handle unauthorized access and redirect the user to the login page. ```APIDOC ## Examples ### Basic usage ```javascript import { query, redirect } from "@solidjs/router"; const getCurrentUser = query(async () => { const response = await fetch("/api/me"); if (response.status === 401) { return redirect("/login"); } return response.json(); }, "currentUser"); ``` ``` -------------------------------- ### Basic Usage Example Source: https://docs.solidjs.com/solid-router/reference/data-apis/revalidate This example demonstrates how to use `revalidate` to refresh a list of todos. The `refreshTodos` function calls `revalidate` with the key of the `getTodos` query, triggering a refetch of the data. ```APIDOC ## Basic usage ```javascript import { For } from "solid-js"; import { createAsync, query, revalidate } from "@solidjs/router"; const getTodos = query(async () => { const response = await fetch("/api/todos"); return response.json() as Promise<{ id: string; title: string }[]>; }, "todos"); function Todos() { const todos = createAsync(() => getTodos(), { initialValue: [] }); function refreshTodos() { void revalidate(getTodos.key); } return ( <>
    {(todo) =>
  • {todo.title}
  • }
); } ``` ``` -------------------------------- ### Reading and Writing Cache Entries Example Source: https://docs.solidjs.com/solid-router/reference/data-apis/query Shows how to manually interact with the query cache using `query.set`, `query.get`, and `query.delete`. ```APIDOC ## Reading and writing cache entries ```typescript const key = getUserProfile.keyFor("123"); query.set(key, { name: "Ada" }); const cached = query.get(key); query.delete(key); ``` ``` -------------------------------- ### Basic usage example Source: https://docs.solidjs.com/solid-router/reference/data-apis/use-submissions Demonstrates how to use the `useSubmissions` hook to display submission status and handle retries. ```typescript import { For, Show } from "solidjs"; import { action, useSubmissions } from "@solidjs/router"; const addTodoAction = action(async (formData: FormData) => { // ... Sends the todo data to the server. }, "addTodo"); function AddTodoForm() { const submissions = useSubmissions(addTodoAction); return (
{(submission) => (
Adding "{submission.input[0].get("name")?.toString()}" (pending...) (completed) {` (Error: ${submission.result?.message})`}
)}
); } ``` -------------------------------- ### Basic Preload Usage Example Source: https://docs.solidjs.com/solid-router/reference/preload-functions/preload Demonstrates how to use the `preload` property with a `query` helper to fetch product data before rendering the product page. The `preloadProduct` function is called with route parameters to fetch data using `getProduct`. ```typescript import { Route, query } from "@solidjs/router"; const getProduct = query(async (id: string) => { const response = await fetch(`/api/products/${id}`); return response.json(); }, "product"); function preloadProduct({ params }) { void getProduct(params.id); } function ProductPage(props) { return

Product {props.params.id}

; } export default function ProductRoutes() { return ( ); } ``` -------------------------------- ### Basic redirect usage in a query Source: https://docs.solidjs.com/solid-router/reference/response-helpers/redirect This example shows how to use the `redirect` helper within a query to navigate to a login page if the user is unauthorized. ```typescript import { query, redirect } from "@solidjs/router"; const getCurrentUser = query(async () => { const response = await fetch("/api/me"); if (response.status === 401) { return redirect("/login"); } return response.json(); }, "currentUser"); ``` -------------------------------- ### Basic Usage Example Source: https://docs.solidjs.com/solid-router/reference/primitives/use-match Demonstrates how to use the useMatch hook to conditionally apply an 'active' class to a navigation link based on the current route. ```APIDOC ### Basic usage ```jsx import { useMatch } from "@solidjs/router"; import { type JSXElement } from "solid-js"; type NavLinkProps = { href: string; children: JSXElement; }; function NavLink(props: NavLinkProps) { const match = useMatch(() => props.href); return ( {props.children} ); } ``` ``` -------------------------------- ### Basic useMatch Example Source: https://docs.solidjs.com/solid-router/reference/primitives/use-match Demonstrates how to use useMatch to add an 'active' class to a navigation link when its href matches the current route. Requires importing useMatch and JSXElement. ```typescript import { useMatch } from "@solidjs/router"; import { type JSXElement } from "solid-js"; type NavLinkProps = { href: string; children: JSXElement; }; function NavLink(props: NavLinkProps) { const match = useMatch(() => props.href); return ( {props.children} ); } ``` -------------------------------- ### Basic MemoryRouter Usage Source: https://docs.solidjs.com/solid-router/reference/components/memory-router Demonstrates basic setup of MemoryRouter with two routes. It initializes memory history and passes it to the MemoryRouter component. ```typescript import { MemoryRouter, Route, createMemoryHistory } from "@solidjs/router"; export default function App() { const history = createMemoryHistory(); return (

Home

} />

About

} />
); } ``` -------------------------------- ### Basic useSubmissions Example Source: https://docs.solidjs.com/solid-router/reference/data-apis/use-submissions Demonstrates basic usage of useSubmissions to display a list of todos, their pending status, results, and provides retry functionality for failed submissions. ```typescript import { For, Show } from "solid-js"; import { action, useSubmissions } from "@solidjs/router"; const addTodoAction = action(async (formData: FormData) => { // ... Sends the todo data to the server. }, "addTodo"); function AddTodoForm() { const submissions = useSubmissions(addTodoAction); return (
{(submission) => (
Adding "{submission.input[0].get("name")?.toString()}" (pending...) (completed) {` (Error: ${submission.result?.message})`}
)}
); } ``` -------------------------------- ### Example with Custom Filter Functions Source: https://docs.solidjs.com/solid-router/reference/primitives/use-match Illustrates using custom filter functions with useMatch to validate route parameters, such as checking the length and extension of a filename. ```APIDOC ### With custom filter functions ```jsx import { useMatch } from "@solidjs/router"; function FileInfo() { const match = useMatch(() => "/files/:type/:name", { type: ["images", "documents", "videos"], name: (name) => name.length > 5 && name.endsWith(".html"), }); return
File: {match()?.params.name}
; } ``` ``` -------------------------------- ### Configure Root Router Component Source: https://docs.solidjs.com/solid-router/getting-started/installation-and-setup This code demonstrates the basic setup for Solid Router by importing necessary components and rendering the Router component within the application's root element. Ensure the target element ('#app') exists in your HTML. ```typescript import { render } from "solid-js/web"; import { Router } from "@solidjs/router"; const wrapper = document.getElementById("app"); if (!wrapper) { throw new Error("Wrapper div not found"); } render(() => , wrapper); ``` -------------------------------- ### Basic useAction Example Source: https://docs.solidjs.com/solid-router/reference/data-apis/use-action Demonstrates how to use the useAction hook to programmatically trigger an action, like liking a post. The action is defined using the action helper and then invoked via the function returned by useAction. ```typescript import { action, useAction } from "@solidjs/router"; const likePost = action(async (id: string) => { return id; }, "likePost"); function LikeButton(props: { id: string }) { const like = useAction(likePost); return ; } ``` -------------------------------- ### Basic A Component Usage Source: https://docs.solidjs.com/solid-router/reference/components/a Demonstrates basic usage of the `A` component within a Solid Router setup, including navigation links and route definitions. The `activeClass` prop is shown for styling active links. ```javascript import { A, Route, Router } from "@solidjs/router"; function Layout(props) { return ( <> {props.children} ); } export default function App() { return (

Home

} />

Docs

} />
); } ``` -------------------------------- ### Logout Action with Redirect Source: https://docs.solidjs.com/solid-router/concepts/actions Use the `redirect` helper to navigate the user to a new page after an action completes. This example demonstrates clearing a session and redirecting to the homepage. ```typescript import { action, redirect } from "@solidjs/router"; import { useSession } from "vinxi/http"; const logoutAction = action(async () => { "use server"; const session = await useSession({ password: process.env.SESSION_SECRET as string, name: "session", }); if (session.data.sessionId) { await session.clear(); await db.session.delete({ id: sessionId }); } throw redirect("/"); }, "logout"); ``` -------------------------------- ### Reading and writing cache entries Source: https://docs.solidjs.com/solid-router/reference/data-apis/query Demonstrates how to manually set, get, and delete cache entries using the `query` static methods. Ensure values set are non-promise types. ```typescript const key = getUserProfile.keyFor("123"); query.set(key, { name: "Ada" }); const cached = query.get(key); query.delete(key); ``` -------------------------------- ### Basic Usage of createAsync Source: https://docs.solidjs.com/solid-router/reference/data-apis/create-async Demonstrates basic usage of createAsync to fetch user data. It uses a query function to define the data fetching logic and then calls createAsync to get a reactive accessor for the user data. ```typescript import { createAsync, query } from "@solidjs/router"; const getCurrentUser = query(async () => { const response = await fetch("/api/current-user"); return response.json() as Promise<{ name: string }>; }, "currentUser"); function UserProfile() { const user = createAsync(() => getCurrentUser()); return
{user()?.name}
; } ``` -------------------------------- ### Basic Route Linking with Anchor Tags Source: https://docs.solidjs.com/solid-router/getting-started/linking-routes Use standard HTML anchor tags to navigate between routes. Ensure your `Router` setup includes the `root` component to wrap your application's routes. ```javascript const App = (props) => ( <>

My Site with lots of pages

{props.children} ); render( () => ( ), document.getElementById("app") ); ``` -------------------------------- ### Basic useSearchParams Example Source: https://docs.solidjs.com/solid-router/reference/primitives/use-search-params Demonstrates how to get the current 'page' query parameter and update it. The page parameter is converted to a number, defaulting to '1' if not present. Clicking the 'Next' button increments the page number in the URL. ```typescript import { useSearchParams } from "@solidjs/router"; function Paginator() { const [params, setParams] = useSearchParams(); const page = () => Number(params.page || "1"); return (
Current Page: {page()}
); } ``` -------------------------------- ### Invalidating Data After a Mutation Example Source: https://docs.solidjs.com/solid-router/reference/response-helpers/json An example demonstrating how to use the `json` helper within an action to invalidate specific queries after a mutation. ```APIDOC ## Examples ### Invalidating Data After a Mutation ``` import { For } from "solid-js"; import { query, action, json, createAsync } from "@solidjs/router"; const getCurrentUserQuery = query(async () => { return await fetch("/api/me").then((response) => response.json()); }, "currentUser"); const getPostsQuery = query(async () => { return await fetch("/api/posts").then((response) => response.json()); }, "posts"); const createPostAction = action(async (formData: FormData) => { const title = formData.get("title")?.toString(); const newPost = await fetch("/api/posts", { method: "POST", body: JSON.stringify({ title }), }).then((response) => response.json()); // Only revalidate the "posts" query. return json(newPost, { revalidate: "posts" }); }, "createPost"); function Posts() { const currentUser = createAsync(() => getCurrentUserQuery()); const posts = createAsync(() => getPostsQuery()); return (

Welcome back {currentUser()?.name}

    {(post) =>
  • {post.title}
  • }
); } ``` ``` -------------------------------- ### Revalidate a Query Argument Example Source: https://docs.solidjs.com/solid-router/reference/data-apis/revalidate This example shows how to revalidate a specific query based on its arguments. `revalidate` is called with `getProjectTasks.keyFor(props.projectId)` to refresh tasks only for the specified project. ```APIDOC ## Revalidate a query argument ```javascript import { createAsync, query, revalidate } from "@solidjs/router"; const getProjectTasks = query(async (projectId: string) => { const response = await fetch(`/api/projects/${projectId}/tasks`); return response.json() as Promise<{ id: string; title: string }[]>; }, "projectTasks"); function ProjectTasks(props: { projectId: string }) { const tasks = createAsync(() => getProjectTasks(props.projectId), { initialValue: [], }); function refreshProjectTasks() { void revalidate(getProjectTasks.keyFor(props.projectId)); } return ( <>
{tasks().length} tasks
); } ``` ``` -------------------------------- ### Import createAsyncStore Source: https://docs.solidjs.com/solid-router/reference/data-apis/create-async-store Import the `createAsyncStore` function from the `@solidjs/router` package. ```typescript import { createAsyncStore } from "@solidjs/router"; ``` -------------------------------- ### Filtering submissions example Source: https://docs.solidjs.com/solid-router/reference/data-apis/use-submissions Shows how to use the optional `filter` parameter in `useSubmissions` to display only specific submissions, such as those that failed validation. ```typescript import { useSubmissions } from "@solidjs/router"; const addTodoAction = action(async (formData: FormData) => { // ... Sends the todo data to the server. }, "addTodo"); function FailedTodos() { const failedSubmissions = useSubmissions( addTodoAction, ([formData]: [FormData]) => { // Filters for submissions that failed a client-side validation const name = formData.get("name")?.toString() ?? ""; return name.length <= 2; } ); return (

Failed submissions:

{(submission) => (
{submission.input[0].get("name")?.toString()}
)}
); } ``` -------------------------------- ### Basic HashRouter Usage Source: https://docs.solidjs.com/solid-router/reference/components/hash-router Demonstrates how to set up a basic HashRouter with a root route. Ensure you have a root element with id 'root' in your HTML. ```typescript import { render } from "solid-js/web"; import { HashRouter, Route } from "@solidjs/router"; render( () => (

Home

} />
), document.getElementById("root")! ); ``` -------------------------------- ### Basic Navigate Usage Source: https://docs.solidjs.com/solid-router/reference/components/navigate Use the Navigate component to redirect from a '/old' route to a '/new' route within a Router setup. ```typescript import { Navigate, Route, Router } from "@solidjs/router"; export default function App() { return ( } /> ); } ``` -------------------------------- ### Basic Usage of useResolvedPath Source: https://docs.solidjs.com/solid-router/reference/primitives/use-resolved-path Use useResolvedPath to get a resolved path for navigation. The resolved path is used as the href for an A component. ```typescript import { A, useResolvedPath } from "@solidjs/router"; function SettingsLink() { const settingsPath = useResolvedPath(() => "settings"); return Settings; } ``` -------------------------------- ### Import useIsRouting Source: https://docs.solidjs.com/solid-router/reference/primitives/use-is-routing Import the useIsRouting hook from the @solidjs/router package. ```javascript import { useIsRouting } from "@solidjs/router"; ``` -------------------------------- ### Import createAsync Source: https://docs.solidjs.com/solid-router/reference/data-apis/create-async Import the createAsync function from the Solid Router library. ```typescript import { createAsync } from "@solidjs/router"; ``` -------------------------------- ### Basic Usage of reload in an action Source: https://docs.solidjs.com/solid-router/reference/response-helpers/reload Use `reload` within an action to specify which queries should be revalidated after the action completes. This example shows revalidating the 'userPreferences' query. ```javascript import { action, reload } from "@solidjs/router"; const savePreferencesAction = action(async () => { // ... Saves the user preferences. // Only revalidate the "userPreferences" query. return reload({ revalidate: ["userPreferences"] }); }, "savePreferences"); ``` -------------------------------- ### Import useNavigate Source: https://docs.solidjs.com/solid-router/reference/primitives/use-navigate Import the useNavigate function from the @solidjs/router package. ```typescript import { useNavigate } from "@solidjs/router"; ``` -------------------------------- ### Basic Usage of useParams Source: https://docs.solidjs.com/solid-router/reference/primitives/use-params Use useParams to get route parameters within a component. Accessing parameters creates a dependency, causing the component to re-render when they change. ```typescript import { createMemo } from "solid-js"; import { useParams } from "@solidjs/router"; // Rendered via function UserPage() { const params = useParams(); // Derived value updates when the route parameter changes. const title = createMemo(() => `Profile for ${params.id}`); return

{title()}

; } ``` -------------------------------- ### Import usePreloadRoute Source: https://docs.solidjs.com/solid-router/reference/primitives/use-preload-route Import the usePreloadRoute hook from the @solidjs/router package. ```javascript import { usePreloadRoute } from "@solidjs/router"; ``` -------------------------------- ### Filtering Submissions with useSubmissions Source: https://docs.solidjs.com/solid-router/reference/data-apis/use-submissions Shows how to filter submissions using a predicate function. This example specifically filters for failed todo submissions based on a client-side validation rule. ```typescript import { useSubmissions } from "@solidjs/router"; const addTodoAction = action(async (formData: FormData) => { // ... Sends the todo data to the server. }, "addTodo"); function FailedTodos() { const failedSubmissions = useSubmissions( addTodoAction, ([formData]: [FormData]) => { // Filters for submissions that failed a client-side validation const name = formData.get("name")?.toString() ?? ""; return name.length <= 2; } ); return (

Failed submissions:

{(submission) => (
{submission.input[0].get("name")?.toString()}
)}
); } ``` -------------------------------- ### Basic usage of useCurrentMatches for Breadcrumbs Source: https://docs.solidjs.com/solid-router/reference/primitives/use-current-matches Demonstrates how to use `useCurrentMatches` to get route matches and then map them to extract breadcrumb information for display. The accessor updates automatically when the location changes. ```typescript import { createMemo } from "solid-js"; import { useCurrentMatches } from "@solidjs/router"; function Breadcrumbs() { const matches = useCurrentMatches(); const breadcrumbs = createMemo(() => matches().map((match) => match.route.info?.breadcrumb) ); return <>{breadcrumbs().join(" / ")}; } ``` -------------------------------- ### createAsync with Suspense and ErrorBoundary Source: https://docs.solidjs.com/solid-router/reference/data-apis/create-async Illustrates integrating createAsync with SolidJS's Suspense and ErrorBoundary components for handling loading states and errors during data fetching. It fetches a list of recipes. ```typescript import { ErrorBoundary, For, Suspense } from "solid-js"; import { createAsync, query } from "@solidjs/router"; type Recipe = { name: string; time: string; }; const getRecipes = query(async () => { const response = await fetch("/api/recipes"); return response.json() as Promise; }, "recipes"); function Recipes() { const recipes = createAsync(() => getRecipes()); return ( Couldn't fetch any recipes.

}> Fetching recipes...

}> {(recipe) => (

{recipe.name}

Cook time: {recipe.time}

)}
); } ``` -------------------------------- ### Optimistic Cart Update with useSubmission Source: https://docs.solidjs.com/solid-router/concepts/actions Use `useSubmission` to access pending action input for temporary UI updates. This example shows how to add an item optimistically to a cart before server confirmation. ```typescript import { For, Show } from "solid-js"; import { query, action, createAsync, useSubmission } from "@solidjs/router"; const getCartQuery = query(async () => { // ... Fetches the current shopping cart items. }, "cart"); const addToCartAction = action(async (formData: FormData) => { // ... Adds a product to the cart. }, "addToCart"); function CartPage() { const cart = createAsync(() => getCartQuery()); const submission = useSubmission(addToCartAction); const optimisticCart = () => { const originalItems = cart() ?? []; if (submission.pending) { const formData = submission.input[0] as FormData; const productId = formData.get("productId")?.toString(); const name = formData.get("name")?.toString(); if (productId && name) { // Add the optimistic line item with a temporary identifier. return [...originalItems, { id: "temp", productId, name, quantity: 1 }]; } } return originalItems; }; return (

Your cart

{(item) =>

{item.name}

}

Add item

); } ``` -------------------------------- ### Import HashRouter Source: https://docs.solidjs.com/solid-router/reference/components/hash-router Import the HashRouter component from the Solid Router library. ```typescript import { HashRouter } from "@solidjs/router"; ``` -------------------------------- ### Basic revalidate usage Source: https://docs.solidjs.com/solid-router/reference/data-apis/revalidate This example demonstrates how to revalidate all cache entries associated with a specific query function using its key. This is useful for implementing a general refresh button for a list of items. ```typescript import { For } from "solid-js"; import { createAsync, query, revalidate } from "@solidjs/router"; const getTodos = query(async () => { const response = await fetch("/api/todos"); return response.json() as Promise<{ id: string; title: string }[]>; }, "todos"); function Todos() { const todos = createAsync(() => getTodos(), { initialValue: [] }); function refreshTodos() { void revalidate(getTodos.key); } return ( <>
    {(todo) =>
  • {todo.title}
  • }
); } ``` -------------------------------- ### Define a Catch-all Route with a Component Source: https://docs.solidjs.com/solid-router/concepts/catch-all Use a route with a path of '*404' to render a specific component when no other routes match. This is the standard way to implement a 404 Not Found page. ```javascript import { Router, Route } from "@solidjs/router" import Home from "./Home"; import About from "./About"; import NotFound from "./NotFound"; const App = () => ( ); ``` -------------------------------- ### Basic useBeforeLeave Example Source: https://docs.solidjs.com/solid-router/reference/primitives/use-before-leave Use `useBeforeLeave` to prevent navigation away from a route if the form data is dirty. The listener checks `props.isDirty()` and calls `event.preventDefault()` if true and the navigation hasn't already been prevented. ```typescript import { useBeforeLeave } from "@solidjs/router"; function Editor(props: { isDirty: () => boolean }) { useBeforeLeave((event) => { if (props.isDirty() && !event.defaultPrevented) { event.preventDefault(); } }); return
{/* fields */}
; } ``` -------------------------------- ### createAsync Behavior Source: https://docs.solidjs.com/solid-router/reference/data-apis/create-async Explains the internal workings of createAsync, including its reliance on createResource and how it handles data fetching and reactivity. ```APIDOC ## Behavior * Calls `createResource` internally. * `fn` receives the previous latest value when the resource has resolved, or `undefined` while unresolved. * The previous-value read is wrapped in `untrack`. * The returned accessor reads the current resource value, and `latest` reads `resource.latest`. * During hydration, `window.fetch` and `Promise` are temporarily replaced with mock implementations while `fn` runs. ``` -------------------------------- ### Import useMatch Source: https://docs.solidjs.com/solid-router/reference/primitives/use-match Import the useMatch hook from the @solidjs/router library. ```typescript import { useMatch } from "@solidjs/router"; ``` -------------------------------- ### Access and Update Search Parameters with useSearchParams Source: https://docs.solidjs.com/solid-router/concepts/search-parameters Use `useSearchParams` to get a reactive object for reading and a function for updating URL query parameters. The setter merges new entries into the current query. ```typescript import { useSearchParams } from "@solidjs/router"; export const App = () => { const [searchParams, setSearchParams] = useSearchParams(); return (
Username: {searchParams.username} { e.preventDefault(); setSearchParams({ username: e.target.value }); }} />
); }; ``` -------------------------------- ### createAsync Parameters Source: https://docs.solidjs.com/solid-router/reference/data-apis/create-async Details the parameters accepted by the createAsync function, including the fetcher function and options. ```APIDOC ## Parameters ### `fn` * **Type:** `(prev: T | undefined) => Promise` * **Required:** Yes Promise-returning function used as the async resource fetcher. The resolved value is returned by the accessor. Synchronous reactive reads made while `fn` runs are tracked, causing the resource to rerun when those dependencies change. ### `options` * **Type:** `{ name?: string; initialValue?: T; deferStream?: boolean }` * **Required:** No Options for the resource name, initial value, and server streaming. #### `name` * **Type:** `string` * **Required:** No Name used by the resource for development debugging. #### `initialValue` * **Type:** `T` * **Required:** No Initial value returned by the accessor before the async function resolves. #### `deferStream` * **Type:** `boolean` * **Default:** `false` * **Required:** No When `true`, streaming waits for this resource to resolve before flushing. ``` -------------------------------- ### Navigation with Solid Router's `` Component Source: https://docs.solidjs.com/solid-router/getting-started/linking-routes Utilize the `` component from Solid Router for enhanced linking capabilities. It automatically handles base URLs and relative paths, simplifying navigation. ```javascript import { lazy } from "solid-js"; import { render } from "solid-js/web"; import { Router, Route, A } from "@solidjs/router"; const Users = lazy(() => import("./pages/Users")); const Home = lazy(() => import("./pages/Home")); const App = (props) => ( <>

My Site with lots of pages

{props.children} ); render( () => ( ), document.getElementById("app") ); ``` -------------------------------- ### useMatch with Parameter Filters Source: https://docs.solidjs.com/solid-router/reference/primitives/use-match Shows how to use useMatch with filters for route parameters. It specifies allowed values for 'lang' and a regex pattern for 'slug'. Requires importing useMatch and Show. ```typescript import { useMatch } from "@solidjs/router"; import { Show } from "solid-js"; function BlogPost() { const match = useMatch(() => "/:lang?/blog/:slug", { lang: ["en", "es", "fr"], slug: /^[a-z0-9-]+$/, }); const lang = () => match()?.params.lang || "en"; return (

Blog slug: {match()?.params.slug}

); } ``` -------------------------------- ### Define Action and Use useSubmission Source: https://docs.solidjs.com/solid-router/reference/data-apis/use-submission Define an action using the 'action' helper and then use the 'useSubmission' hook to access its latest submission state within a component. This example demonstrates how to display a 'Saving...' message when a form submission is pending. ```typescript import { Show } from "solid-js"; import { action, useSubmission } from "@solidjs/router"; const addTodo = action(async (data: URLSearchParams) => { return data.get("title")?.toString(); }, "addTodo"); function TodoForm() { const submission = useSubmission(addTodo); return (
Saving...
); } ``` -------------------------------- ### Import useBeforeLeave Source: https://docs.solidjs.com/solid-router/reference/primitives/use-before-leave Import the `useBeforeLeave` hook from the `@solidjs/router` package. ```typescript import { useBeforeLeave } from "@solidjs/router"; ``` -------------------------------- ### Navigation with State Option Source: https://docs.solidjs.com/solid-router/reference/primitives/use-navigate Demonstrates passing custom state data during navigation using the `state` option. ```APIDOC ## Example: With `state` ```javascript import { useNavigate } from "@solidjs/router"; const navigate = useNavigate(); // Pass custom state navigate("/checkout", { state: { from: "cart", total: 100 }, }); ``` ``` -------------------------------- ### Invalidating Data After a Mutation Source: https://docs.solidjs.com/solid-router/reference/response-helpers/json This example demonstrates how to use the `json` helper within an action to revalidate specific queries after a data mutation. It shows setting up queries, an action to create a post, and a component to display posts and a form to create new ones. ```typescript import { For } from "solid-js"; import { query, action, json, createAsync } from "@solidjs/router"; const getCurrentUserQuery = query(async () => { return await fetch("/api/me").then((response) => response.json()); }, "currentUser"); const getPostsQuery = query(async () => { return await fetch("/api/posts").then((response) => response.json()); }, "posts"); const createPostAction = action(async (formData: FormData) => { const title = formData.get("title")?.toString(); const newPost = await fetch("/api/posts", { method: "POST", body: JSON.stringify({ title }), }).then((response) => response.json()); // Only revalidate the "posts" query. return json(newPost, { revalidate: "posts" }); }, "createPost"); function Posts() { const currentUser = createAsync(() => getCurrentUserQuery()); const posts = createAsync(() => getPostsQuery()); return (

Welcome back {currentUser()?.name}

    {(post) =>
  • {post.title}
  • }
); } ``` -------------------------------- ### Revalidate a specific query argument Source: https://docs.solidjs.com/solid-router/reference/data-apis/revalidate This example shows how to revalidate a cache entry for a query that accepts arguments, using `keyFor` to target a specific set of arguments. This is useful when you need to refresh data for a particular item, like tasks for a specific project. ```typescript import { createAsync, query, revalidate } from "@solidjs/router"; const getProjectTasks = query(async (projectId: string) => { const response = await fetch(`/api/projects/${projectId}/tasks`); return response.json() as Promise<{ id: string; title: string }[]>; }, "projectTasks"); function ProjectTasks(props: { projectId: string }) { const tasks = createAsync(() => getProjectTasks(props.projectId), { initialValue: [], }); function refreshProjectTasks() { void revalidate(getProjectTasks.keyFor(props.projectId)); } return ( <>
{tasks().length} tasks
); } ``` -------------------------------- ### Import Navigate Component Source: https://docs.solidjs.com/solid-router/reference/components/navigate Import the Navigate component from the @solidjs/router package. ```typescript import { Navigate } from "@solidjs/router"; ``` -------------------------------- ### Import the A Component Source: https://docs.solidjs.com/solid-router/reference/components/a Import the `A` component from the `@solidjs/router` package. ```javascript import { A } from "@solidjs/router"; ``` -------------------------------- ### Netlify Redirects for SPA Source: https://docs.solidjs.com/solid-router/rendering-modes/spa Use a `_redirects` file to configure Netlify to redirect all paths to `index.html` for SPA routing. ```plaintext /* /index.html 200 ```