### Configure SPA Redirects for Deployment
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Provides configuration examples for handling client-side routing in SPAs by redirecting all requests to index.html on Netlify and Vercel.
```shell
/* /index.html 200
```
```json
{
"rewrites": [
{
"source": "/(.*)",
"destination": "/index.html"
}
]
}
```
--------------------------------
### Define Wildcard Route
Source: https://github.com/solidjs/solid-router/blob/main/README.md
This example demonstrates how to create a wildcard route in Solid Router using the asterisk (`*`) character. The path `foo/*` will match any URL that starts with `foo/`, including `foo/`, `foo/a/`, and `foo/a/b/c`. You can also name the wildcard segment, like `foo/*any`, to capture the matched part of the path and expose it as a parameter to the component. Note that the wildcard must be the last part of the path.
```jsx
// Matches any path that begins with foo, including foo/, foo/a/, foo/a/b/c
```
```jsx
```
--------------------------------
### Setup Solid Router with JSX
Source: https://context7.com/solidjs/solid-router/llms.txt
Demonstrates setting up the main browser router component for history-based navigation in a SolidJS application. It imports necessary components, defines routes with lazy-loaded components, and renders the application within the Router.
```jsx
import { render } from "solid-js/web";
import { Router, Route } from "@solidjs/router";
import { lazy } from "solid-js";
const Home = lazy(() => import("./pages/Home"));
const Users = lazy(() => import("./pages/Users"));
const User = lazy(() => import("./pages/User"));
const NotFound = lazy(() => import("./pages/NotFound"));
const App = (props) => (
<>
My Application
{props.children}
>
);
render(
() => (
),
document.getElementById("app")
);
```
--------------------------------
### Implement alternative router modes in Solid Router
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Examples of using HashRouter for URL hash-based navigation, MemoryRouter for testing environments, and configuring the Router for SSR by passing a URL.
```jsx
import { HashRouter } from "@solidjs/router";
;
```
```jsx
import { MemoryRouter } from "@solidjs/router";
;
```
```jsx
import { isServer } from "solid-js/web";
import { Router } from "@solidjs/router";
;
```
--------------------------------
### Setup HashRouter with JSX
Source: https://context7.com/solidjs/solid-router/llms.txt
Shows how to configure Solid Router using `HashRouter` for navigation based on URL hashes. This is useful in environments where server-side routing configuration is not feasible. URLs will appear with a hash prefix, e.g., `/#/about`.
```jsx
import { render } from "solid-js/web";
import { HashRouter, Route } from "@solidjs/router";
const Home = () =>
Home
;
const About = () =>
About
;
// URLs will be: /#/, /#/about, /#/users/123
render(
() => (
),
document.getElementById("app")
);
```
--------------------------------
### Setup MemoryRouter for Testing
Source: https://context7.com/solidjs/solid-router/llms.txt
Demonstrates the use of `MemoryRouter` for testing purposes or in non-browser environments where actual URL changes are not desired. It allows for programmatic control of navigation history and listening to route changes.
```jsx
import { render } from "solid-js/web";
import { MemoryRouter, createMemoryHistory, Route } from "@solidjs/router";
// Create custom memory history
const history = createMemoryHistory();
// Navigate programmatically
history.set({ value: "/users/123", scroll: false, replace: false });
// Go back/forward
history.back();
history.forward();
history.go(-2);
// Listen to changes
const unsubscribe = history.listen((value) => {
console.log("Route changed to:", value);
});
render(
() => (
),
document.getElementById("app")
);
```
--------------------------------
### Install Solid Router via NPM
Source: https://github.com/solidjs/solid-router/blob/main/README.md
The command to add the @solidjs/router package to your project using the npm package manager.
```bash
npm add @solidjs/router
```
--------------------------------
### Create data mutations with action
Source: https://context7.com/solidjs/solid-router/llms.txt
Defines data mutation functions that support form submissions, cache invalidation, and redirects. It includes examples for basic usage, typed arguments via .with(), and lifecycle callbacks.
```jsx
import { action, useAction, useSubmission, redirect, reload } from "@solidjs/router";
const addTodo = action(async (formData) => {
const title = formData.get("title");
await fetch("/api/todos", {
method: "POST",
body: JSON.stringify({ title })
});
});
const createUser = action(async (formData) => {
const user = await api.createUser({
name: formData.get("name"),
email: formData.get("email")
});
throw redirect(`/users/${user.id}`);
}, "createUser");
const updateTodo = action(async (id, completed) => {
await api.updateTodo(id, { completed });
throw reload({ revalidate: getTodos.key });
}, "updateTodo");
function TodoForm() {
return (
);
}
```
--------------------------------
### Validate Route Parameters with MatchFilters
Source: https://github.com/solidjs/solid-router/blob/main/README.md
This example shows how to use `MatchFilters` in Solid Router to validate dynamic route parameters. The `matchFilters` prop is applied to a `Route` component, allowing you to define validation logic for each parameter. This ensures that only URLs matching the specified criteria (e.g., specific string values, regular expressions, or custom functions) will render the associated component. If validation fails, the route will not match.
```jsx
import { lazy } from "solid-js";
import { render } from "solid-js/web";
import { Router, Route } from "@solidjs/router";
import type { MatchFilters } from "@solidjs/router";
const User = lazy(() => import("./pages/User"));
const filters: MatchFilters = {
parent: ["mom", "dad"], // allow enum values
id: /^\d+$/, // only allow numbers
withHtmlExtension: (v: string) => v.length > 5 && v.endsWith(".html"), // we want an `*.html` extension
};
render(
() => (
),
document.getElementById("app")
);
```
--------------------------------
### Create Async Store with Deep Reactivity
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Introduces `createAsyncStore`, which is similar to `createAsync` but leverages a deeply reactive store. This is ideal for managing and updating large datasets with fine-grained control.
```jsx
const todos = createAsyncStore(() => getTodos());
```
--------------------------------
### Create Navigation Links
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Demonstrates how to use standard anchor tags within a layout to navigate between defined routes in a Solid Router application.
```jsx
import { lazy } from "solid-js";
import { render } from "solid-js/web";
import { Router, Route } 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")
);
```
--------------------------------
### Configure Basic Routes with Solid Router
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Demonstrates how to define application routes using the Router and Route components. It maps specific URL paths to corresponding components to be rendered.
```jsx
import { render } from "solid-js/web";
import { Router, Route } from "@solidjs/router";
import Home from "./pages/Home";
import Users from "./pages/Users";
render(
() => (
),
document.getElementById("app")
);
```
--------------------------------
### Modularize Preload Logic in Route Data Files
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Shows the recommended pattern of separating preload logic into dedicated data files. This approach improves performance by allowing data functions to be imported independently of the main component code.
```javascript
import { lazy } from "solid-js";
import { Route } from "@solidjs/router";
import preloadUser from "./pages/users/[id].data.js";
const User = lazy(() => import("/pages/users/[id].js"));
// In the Route definition
;
```
--------------------------------
### Implement Root Layouts and Catch-all Routes
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Shows how to wrap routes in a persistent root layout and define a catch-all route for 404 error handling. The root component receives children to render the active route content.
```jsx
import { render } from "solid-js/web";
import { Router, Route } from "@solidjs/router";
import Home from "./pages/Home";
import Users from "./pages/Users";
import NotFound from "./pages/404";
const App = (props) => (
<>
My Site with lots of pages
{props.children}
>
);
render(
() => (
),
document.getElementById("app")
);
```
--------------------------------
### Define Routes with Route Component
Source: https://context7.com/solidjs/solid-router/llms.txt
Illustrates various ways to define routes using the `Route` component in Solid Router. It covers basic, dynamic, optional, and wildcard routes, as well as route matching with filters, multiple paths, nested routes, preload functions, and route metadata.
```jsx
import { Route } from "@solidjs/router";
import { lazy } from "solid-js";
const User = lazy(() => import("./pages/User"));
// Basic route
// Dynamic route with parameters
// Optional parameters
// Wildcard routes
// Route with match filters for parameter validation
const filters = {
parent: ["mom", "dad"],
id: /^\d+$/,
ext: (v) => v.endsWith(".html")
};
// Multiple paths (won't re-render when switching between them)
// Nested routes with children
// Route with preload function
function preloadUser({ params, location, intent }) {
void getUser(params.id);
}
// Route with metadata
```
--------------------------------
### Create Async Data Fetching with createAsync
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Utilizes the `createAsync` primitive, a lightweight wrapper around `createResource`, for handling asynchronous operations. It tracks functions like `createMemo` and manages promises, triggering Suspense/Transitions when data is not yet ready.
```jsx
const user = createAsync((currentValue) => getUser(params.id));
```
```jsx
const user = createAsync((currentValue) => getUser(params.id));
return
{user.latest.name}
;
```
--------------------------------
### Configure Route Preloading in Solid Router
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Demonstrates how to manually implement data preloading by disabling default router preloads and using a custom preload function. This pattern allows for manual context injection within route components.
```javascript
import { lazy } from "solid-js";
import { Route } from "@solidjs/router";
const User = lazy(() => import("./pages/users/[id].js"));
// preload function
function preloadUser({ params, location }) {
const [user] = createResource(() => params.id, fetchUser);
return user;
}
// Pass it in the route definition
;
```
--------------------------------
### Navigate programmatically with useNavigate
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Retrieves a function to perform programmatic navigation. Supports options like replacing history entries, resolving paths, and passing custom state.
```javascript
const navigate = useNavigate();
if (unauthorized) {
navigate("/login", { replace: true });
}
```
--------------------------------
### Implement Redirect with Solid Router
Source: https://github.com/solidjs/solid-router/blob/main/README.md
The `redirect` response helper is used to navigate to a different route. It is typically thrown from query or action functions to halt execution and trigger a navigation. Options can include invalidation hints.
```js
const getUser = query(() => {
const user = await api.getCurrentUser()
if (!user) throw redirect("/login");
return user;
})
```
--------------------------------
### Initialize Solid Router in Application
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Configures the root Router component within a SolidJS application using the render function. This enables the router to match URLs and manage page navigation.
```jsx
import { render } from "solid-js/web";
import { Router } from "@solidjs/router";
render(() => , document.getElementById("app"));
```
--------------------------------
### Create Redirect Responses with redirect (SolidJS)
Source: https://context7.com/solidjs/solid-router/llms.txt
The `redirect` helper creates a response that triggers navigation. It can be used within queries or actions to redirect users to a different route, optionally with a specific status code or revalidation instructions.
```jsx
import { redirect, query, action } from "@solidjs/router";
// Redirect in query (e.g., auth check)
const getCurrentUser = query(async () => {
const user = await api.getCurrentUser();
if (!user) {
throw redirect("/login");
}
return user;
}, "currentUser");
// Redirect with status code
const legacyRedirect = query(async (oldId) => {
const newId = await api.getNewId(oldId);
throw redirect(`/items/${newId}`, 301); // Permanent redirect
}, "legacyRedirect");
// Redirect with revalidation
const createPost = action(async (formData) => {
const post = await api.createPost(formData);
throw redirect(`/posts/${post.id}`, {
revalidate: "posts" // Invalidate posts cache
});
}, "createPost");
// Redirect with multiple revalidations
const transferItem = action(async (itemId, toUserId) => {
await api.transferItem(itemId, toUserId);
throw redirect("/inventory", {
revalidate: ["inventory", `user-items-${toUserId}`]
});
}, "transferItem");
// Conditional redirect
const checkAccess = query(async (resourceId) => {
const access = await api.checkAccess(resourceId);
if (!access.allowed) {
throw redirect("/unauthorized", {
status: 403
});
}
return access.resource;
}, "checkAccess");
```
--------------------------------
### Match routes with useMatch
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Creates a memoized value that returns match information if the current path matches the provided path accessor.
```javascript
const match = useMatch(() => props.href);
return ;
```
--------------------------------
### Manage query parameters with useSearchParams
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Returns a tuple with a reactive object for reading search parameters and a setter function for updating them. Updates trigger navigation and support standard navigation options.
```javascript
const [searchParams, setSearchParams] = useSearchParams();
return (
Page: {searchParams.page}
);
```
--------------------------------
### Define routes using arrays or objects in Solid Router
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Demonstrates how to configure routes using an array of route definitions or a single object. This approach allows for lazy loading components and defining nested route structures.
```jsx
import { lazy } from "solid-js";
import { render } from "solid-js/web";
import { Router } from "@solidjs/router";
const routes = [
{
path: "/users",
component: lazy(() => import("/pages/users.js")),
},
{
path: "/users/:id",
component: lazy(() => import("/pages/users/[id].js")),
children: [
{ path: "/", component: lazy(() => import("/pages/users/[id]/index.js")) },
{ path: "/settings", component: lazy(() => import("/pages/users/[id]/settings.js")) },
{ path: "/*all", component: lazy(() => import("/pages/users/[id]/[...all].js")) },
],
},
{ path: "/", component: lazy(() => import("/pages/index.js")) },
{ path: "/*all", component: lazy(() => import("/pages/[...all].js")) },
];
render(() => {routes}, document.getElementById("app"));
```
```jsx
const route = {
path: "/",
component: lazy(() => import("/pages/index.js")),
};
render(() => {route}, document.getElementById("app"));
```
--------------------------------
### Monitor routing status with useIsRouting
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Provides a signal indicating if the application is currently in a transition state. Ideal for displaying loading indicators during concurrent rendering.
```javascript
const isRouting = useIsRouting();
return (
);
```
--------------------------------
### Define Nested Routes in Solid Router
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Demonstrates equivalent ways to define nested routes. Shows how to structure routes using flat definitions versus nested JSX components and clarifies how to ensure parent components are rendered as routes.
```jsx
// Explicit parent route definition
```
--------------------------------
### Accessing Query Key and Invalidation Methods
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Demonstrates how to access the query key and use key-based methods for invalidation. The `key` property returns the base key, while `keyFor` generates a specific key for given arguments.
```ts
let id = 5;
getUser.key; // returns "users"
getUser.keyFor(id); // returns "users[5]"
```
--------------------------------
### Preload routes with usePreloadRoute
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Returns a function to manually trigger route preloading. This is useful for optimizing performance by loading data before a user navigates to a specific path.
```javascript
const preload = usePreloadRoute();
preload(`/users/settings`, { preloadData: true });
```
--------------------------------
### Define and Register Preload Function in Solid Router
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Demonstrates how to define a preload function that receives route parameters and location data, and how to register it within a Route component. This allows for eager data fetching when a route is accessed or hovered.
```javascript
import { lazy } from "solid-js";
import { Route } from "@solidjs/router";
const User = lazy(() => import("./pages/users/[id].js"));
// preload function
function preloadUser({ params, location }) {
// do preloading
}
// Pass it in the route definition
;
```
--------------------------------
### Invoke actions programmatically with useAction
Source: https://context7.com/solidjs/solid-router/llms.txt
Provides a hook to wrap actions for programmatic execution outside of standard form submissions. Useful for event handlers like button clicks or toggle changes.
```jsx
import { action, useAction } from "@solidjs/router";
const updateSettings = action(async (settings) => {
await api.updateSettings(settings);
}, "updateSettings");
function SettingsPanel() {
const submitSettings = useAction(updateSettings);
const handleToggle = async (setting, value) => {
try {
await submitSettings({ [setting]: value });
showToast("Settings updated");
} catch (error) {
showToast("Failed to update settings");
}
};
return (
);
}
```
--------------------------------
### Inject Data via Context in Solid Components
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Shows how to consume data passed through route props and provide it to child components using the Context API, effectively reproducing legacy data patterns.
```javascript
function User(props) {
{/* my component content */}
;
}
// Somewhere else
function UserDetails() {
const user = useContext(UserContext);
// render stuff
}
```
--------------------------------
### Manage Optimistic Updates with useSubmission/useSubmissions
Source: https://github.com/solidjs/solid-router/blob/main/README.md
The `useSubmission` and `useSubmissions` hooks are used to inject optimistic updates while actions are in flight. `useSubmissions` returns all matching submissions with an optional filter, while `useSubmission` returns the latest single submission.
```typescript
type Submission = {
readonly input: T;
readonly result?: U;
readonly pending: boolean;
readonly url: string;
clear: () => void;
retry: () => void;
};
const submissions = useSubmissions(action, (input) => filter(input));
const submission = useSubmission(action, (input) => filter(input));
```
--------------------------------
### Handle complex reactive data with createAsyncStore
Source: https://context7.com/solidjs/solid-router/llms.txt
createAsyncStore returns a deeply reactive store instead of a signal, which is ideal for complex data structures. It supports fine-grained reactivity, allowing specific nested properties to trigger updates without re-rendering the entire object.
```jsx
import { createAsyncStore, query } from "@solidjs/router";
const getTodos = query(async () => {
const res = await fetch("/api/todos");
return res.json();
}, "todos");
function TodoList() {
const todos = createAsyncStore(() => getTodos(), {
reconcile: { key: "id" }
});
return (
{(todo) =>
{todo.title}
}
);
}
```
--------------------------------
### Manage reactive async state with createAsync
Source: https://context7.com/solidjs/solid-router/llms.txt
createAsync transforms an async function into a reactive signal, integrating directly with Suspense for loading states. It supports initial values, access to previous data during refetches, and debugging names.
```jsx
import { createAsync, query } from "@solidjs/router";
const getUser = query(async (id) => {
const res = await fetch(`/api/users/${id}`);
return res.json();
}, "users");
function UserProfile() {
const params = useParams();
const user = createAsync(() => getUser(params.id), {
initialValue: { name: "Loading...", email: "" }
});
return
{user()?.email}
;
}
```
--------------------------------
### useIsRouting Hook for Loading Indicators in SolidJS
Source: https://context7.com/solidjs/solid-router/llms.txt
The useIsRouting hook returns a signal that indicates whether a route transition is currently in progress. This is particularly useful for implementing visual loading indicators or dimming content during navigation. It takes no arguments and returns a boolean signal.
```jsx
import { useIsRouting } from "@solidjs/router";
function App(props) {
const isRouting = useIsRouting();
return (
{isRouting() && (
)}
{props.children}
);
}
// Show stale content with loading overlay
function PageContent(props) {
const isRouting = useIsRouting();
return (
);
}
```
--------------------------------
### Define Route with Multiple Paths
Source: https://github.com/solidjs/solid-router/blob/main/README.md
This snippet shows how to define a single route in Solid Router that can match multiple URL paths by providing an array of strings to the `path` prop. This is beneficial for scenarios where you want a component to handle different but related URLs without causing a re-render when navigating between them. For instance, navigating from `/login` to `/register` will keep the `Login` component mounted.
```jsx
// Navigating from login to register does not cause the Login component to re-render
```
--------------------------------
### Implement Layout Wrappers with Nested Routes
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Shows how to use a parent component to wrap nested routes using props.children. This pattern is useful for shared layouts or headers across multiple sub-routes.
```jsx
function PageWrapper(props) {
return (
);
}
```
--------------------------------
### useNavigate Hook for Programmatic Routing in SolidJS
Source: https://context7.com/solidjs/solid-router/llms.txt
The useNavigate hook returns a function for programmatic navigation. This function allows developers to imperatively change routes, with options to replace the current history entry, control scroll behavior, resolve relative paths, and pass state to the target route. It also supports navigating back or forward in the history stack.
```jsx
import { useNavigate } from "@solidjs/router";
function LoginForm() {
const navigate = useNavigate();
const handleLogin = async (credentials) => {
const result = await authenticate(credentials);
if (result.success) {
// Basic navigation
navigate("/dashboard");
// Replace current history entry
navigate("/dashboard", { replace: true });
// Prevent scroll to top
navigate("/dashboard", { scroll: false });
// Pass state
navigate("/dashboard", {
state: { welcomeMessage: "Login successful!" }
});
// Navigate with all options
navigate("/dashboard", {
replace: true,
scroll: false,
resolve: true,
state: { user: result.user }
});
}
};
// Navigate back/forward in history
const goBack = () => navigate(-1);
const goForward = () => navigate(1);
const goBackTwo = () => navigate(-2);
return (
);
}
```
--------------------------------
### usePreloadRoute Hook for Prefetching Routes in SolidJS
Source: https://context7.com/solidjs/solid-router/llms.txt
The usePreloadRoute hook provides a function to manually preload a route and its associated data. This is beneficial for improving perceived performance, often implemented on hover states or focus events for links. It accepts the route path and an options object, with `preloadData` being a key parameter.
```jsx
import { usePreloadRoute } from "@solidjs/router";
function Navigation() {
const preload = usePreloadRoute();
return (
);
}
// Preload dynamically
function UserList(props) {
const preload = usePreloadRoute();
return (
{(user) => (
preload(`/users/${user.id}`, { preloadData: true })}
>
{user.name}
)}
);
}
```
--------------------------------
### Intercept navigation with useBeforeLeave
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Registers a callback that executes before leaving a route. Allows for preventing navigation, prompting users for confirmation, and retrying navigation.
```typescript
useBeforeLeave((e: BeforeLeaveEventArgs) => {
if (form.isDirty && !e.defaultPrevented) {
e.preventDefault();
setTimeout(() => {
if (window.confirm("Discard unsaved changes - are you sure?")) {
e.retry(true);
}
}, 100);
}
});
```
--------------------------------
### useMatch Hook
Source: https://context7.com/solidjs/solid-router/llms.txt
Determines if the current route matches a given pattern, enabling conditional rendering based on route matching. It can also handle dynamic route parameters and filters.
```APIDOC
## useMatch
### Description
Hook that returns match information if the current path matches a given pattern, useful for conditional rendering.
### Method
N/A (Hook)
### Endpoint
N/A (Hook)
### Parameters
N/A (Hook)
### Request Example
```jsx
import { useMatch } from "@solidjs/router";
import { Show } from "solid-js";
function Navigation() {
const matchUsers = useMatch(() => "/users/*");
const matchUserProfile = useMatch(() => "/users/:id");
const matchAdmin = useMatch(() => "/admin");
return (
);
}
// With match filters
function FilteredMatch() {
const matchNumericId = useMatch(
() => "/users/:id",
{ id: /^\d+$/ } // Only match numeric IDs
);
return (
Valid numeric user ID: {matchNumericId().params.id}
);
}
```
### Response
N/A (Hook returns match information)
#### Success Response (N/A)
#### Response Example
N/A
```
--------------------------------
### Track Form Submissions with useSubmission and useSubmissions (SolidJS)
Source: https://context7.com/solidjs/solid-router/llms.txt
These hooks track the state of actions, enabling optimistic UI updates and loading indicators. `useSubmission` tracks the most recent submission, while `useSubmissions` tracks all pending submissions for a given action. They are useful for providing immediate feedback to users during data operations.
```jsx
import { action, useSubmission, useSubmissions } from "@solidjs/router";
import { Show, For } from "solid-js";
const addTodo = action(async (formData) => {
const title = formData.get("title");
await new Promise(r => setTimeout(r, 1000)); // Simulate delay
return api.createTodo({ title });
}, "addTodo");
// Track single submission (most recent)
function TodoForm() {
const submission = useSubmission(addTodo);
return (
);
}
// Track all submissions
function TodoListWithOptimistic() {
const submissions = useSubmissions(addTodo);
const todos = createAsyncStore(() => getTodos());
return (
);
}
```
--------------------------------
### Create cached async queries with Solid Router
Source: https://context7.com/solidjs/solid-router/llms.txt
The query function creates a cached, async data fetching utility that supports deduplication, revalidation, and SSR. It provides a key-based system for granular cache invalidation and can be used with preload functions or reactive components.
```jsx
import { query, createAsync, revalidate } from "@solidjs/router";
const getUser = query(async (id) => {
const response = await fetch(`/api/users/${id}`);
if (!response.ok) throw new Error("User not found");
return response.json();
}, "users");
// Invalidation examples
await revalidate(getUser.keyFor(123));
await revalidate(getUser.key);
await revalidate(["users", "posts"]);
```
--------------------------------
### Implement Reload with Solid Router
Source: https://github.com/solidjs/solid-router/blob/main/README.md
The `reload` response helper is used to revalidate and reload data on the current page. It can be thrown from action functions and accepts options like `revalidate` to specify which data to refresh.
```js
const getTodo = query(async (id: number) => {
const todo = await fetchTodo(id);
return todo;
}, "todo");
const updateTodo = action(async (todo: Todo) => {
await updateTodo(todo.id, todo);
reload({ revalidate: getTodo.keyFor(todo.id) });
});
```
--------------------------------
### Retrieve route matches with useCurrentMatches
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Returns an array of all matches for the current route. Useful for accessing route-specific metadata like breadcrumbs.
```javascript
const matches = useCurrentMatches();
const breadcrumbs = createMemo(() =>
matches().map((m) => m.route.info.breadcrumb)
);
```
--------------------------------
### Define and Use Solid Router Actions
Source: https://github.com/solidjs/solid-router/blob/main/README.md
Actions are used for data mutations in Solid Router. They can be defined globally and used within forms via the `action` attribute or `formaction` button attribute. Actions only support POST requests. The `with` method allows for typed data arguments instead of FormData.
```jsx
import { action, revalidate, redirect } from "@solidjs/router"
// anywhere
const myAction = action(async (data) => {
await doMutation(data);
throw redirect("/", { revalidate: getUser.keyFor(data.id) }); // throw a response to do a redirect
});
// in component
//or
```
```js
const deleteTodo = action(async (formData: FormData) => {
const id = Number(formData.get("id"))
await api.deleteTodo(id)
})
```
```js
const deleteTodo = action(api.deleteTodo)
```
```jsx
const myAction = action(async (args) => {}, "my-action");
```
--------------------------------
### Use Solid Router Action Directly with useAction
Source: https://github.com/solidjs/solid-router/blob/main/README.md
The `useAction` primitive allows you to use actions directly outside of a form context. This requires client-side JavaScript and is not progressively enhanceable like form-based actions. It preserves types when used with custom data.
```jsx
// in component
const submit = useAction(myAction);
submit(...args);
```
--------------------------------
### useLocation Hook
Source: https://context7.com/solidjs/solid-router/llms.txt
Provides a reactive location object containing details about the current URL, including pathname, search string, hash, query parameters, state, and a unique key.
```APIDOC
## useLocation
### Description
Hook that returns a reactive location object with pathname, search, hash, query, state, and key.
### Method
N/A (Hook)
### Endpoint
N/A (Hook)
### Parameters
N/A (Hook)
### Request Example
```jsx
import { useLocation } from "@solidjs/router";
import { createMemo, createEffect } from "solid-js";
function LocationDisplay() {
const location = useLocation();
// Create derived values
const isUserPage = createMemo(() =>
location.pathname.startsWith("/users")
);
// React to location changes
createEffect(() => {
console.log("Path changed:", location.pathname);
console.log("Search:", location.search);
console.log("Hash:", location.hash);
console.log("Query params:", location.query);
console.log("State:", location.state);
});
// Access navigation state passed from previous page
const welcomeMessage = () => location.state?.welcomeMessage;
return (
Current path: {location.pathname}
Search string: {location.search}
Hash: {location.hash}
Query 'page': {location.query.page}
{welcomeMessage() &&
{welcomeMessage()}
}
{isUserPage() && }
);
}
```
### Response
N/A (Hook returns reactive state)
#### Success Response (N/A)
#### Response Example
N/A
```
--------------------------------
### Perform conditional rendering with useMatch
Source: https://context7.com/solidjs/solid-router/llms.txt
The useMatch hook checks if the current route matches a specific pattern. It supports path parameters and custom filters, making it useful for highlighting active navigation items or rendering specific components based on the current route.
```jsx
import { useMatch } from "@solidjs/router";
import { Show } from "solid-js";
function Navigation() {
const matchUsers = useMatch(() => "/users/*");
const matchUserProfile = useMatch(() => "/users/:id");
const matchAdmin = useMatch(() => "/admin");
return (
);
}
function FilteredMatch() {
const matchNumericId = useMatch(
() => "/users/:id",
{ id: /^\d+$/ }
);
return (
Valid numeric user ID: {matchNumericId().params.id}
);
}
```
--------------------------------
### Define Optional Route Parameter
Source: https://github.com/solidjs/solid-router/blob/main/README.md
This code snippet illustrates how to define an optional route parameter in Solid Router by appending a question mark (`?`) to the parameter name. The route `/stories/:id?` will match both `/stories` and `/stories/123`, but not `/stories/123/comments`. This is useful for parameters that may or may not be present in the URL.
```jsx
// Matches stories and stories/123 but not stories/123/comments
```