Skip to content

Commit

Permalink
feat: get router docs up to date (#886)
Browse files Browse the repository at this point in the history
  • Loading branch information
danieljcafonso authored Sep 25, 2024
1 parent b3f39c8 commit 8ada8a7
Show file tree
Hide file tree
Showing 16 changed files with 5,399 additions and 4,185 deletions.
9,070 changes: 5,129 additions & 3,941 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

302 changes: 145 additions & 157 deletions src/routes/guides/routing-and-navigation.mdx

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions src/routes/solid-router/reference/components/route.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ title: Route
`Route` is the component used when defining the routes of an application.
This component is used to define the structure of the application and the components that will be rendered for each route.


<Callout title="Multiple paths">
Routes support defining multiple paths using an array.
This is useful for when you want a route to remain mounted and not re-render when switching between two or more locations that it matches:
Expand All @@ -15,12 +14,13 @@ This is useful for when you want a route to remain mounted and not re-render whe
```

This would mean navigating from `/login` to `/register` would not cause the `Login` component to re-render.

</Callout>

| prop | type | description |
| ------------ | --------------- | ----------------------------------------------------------------- |
| path | `string \| string[]` | Path partial for defining the route segment |
| component | `Component` | Component that will be rendered for the matched segment |
| matchFilters | `MatchFilters` | Additional constraints for matching against the route |
| children | `JSX.Element` | Nested `<Route>` definitions |
| load | `RouteLoadFunc` | Function called during preload or when the route is navigated to. |
| prop | type | description |
| ------------ | -------------------- | ----------------------------------------------------------------- |
| path | `string \| string[]` | Path partial for defining the route segment |
| component | `Component` | Component that will be rendered for the matched segment |
| matchFilters | `MatchFilters` | Additional constraints for matching against the route |
| children | `JSX.Element` | Nested `<Route>` definitions |
| preload | `RoutePreloadFunc` | Function called during preload or when the route is navigated to. |
39 changes: 19 additions & 20 deletions src/routes/solid-router/reference/components/router.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,25 @@ There is an optional `root` prop that can be used to wrap the entire application
import { render } from "solid-js/web";
import { Router, Route } from "@solidjs/router";

const App = props => (
<>
<h1>Root header</h1>
{props.children}
</>
)
const App = (props) => (
<>
<h1>Root header</h1>
{props.children}
</>
);

render(() => (
<Router root={App}>
{/*... routes */}
</Router>
), document.getElementById("app"));
render(
() => <Router root={App}>{/*... routes */}</Router>,
document.getElementById("app")
);
```

| prop | type | description |
| ------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------- |
| children | `JSX.Element`, `RouteDefinition`, or `RouteDefinition[]` | The route definitions |
| root | Component | Top level layout component |
| base | string | Base url to use for matching routes |
| actionBase | string | Root url for server actions, default: `/_server` |
| preload | boolean | Enables/disables preloads globally, default: `true` |
| explicitLinks | boolean | Disables all anchors being intercepted and instead requires `<A>`. default: `false` |
| url | string | The initial route to render |
| prop | type | description |
| ------------- | -------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| children | `JSX.Element`, `RouteDefinition`, or `RouteDefinition[]` | The route definitions |
| root | Component | Top level layout component |
| base | string | Base url to use for matching routes |
| actionBase | string | Root url for server actions, default: `/_server` |
| preload | boolean | Enables/disables preloads globally, default: `true` |
| explicitLinks | boolean | Disables all anchors being intercepted and instead requires `<A>`. default: `false`. (To disable interception for a specific link, set `target` to any value, e.g. `<a target="_self">`.) |
| url | string | The initial route to render |
36 changes: 19 additions & 17 deletions src/routes/solid-router/reference/data-apis/cache.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ title: cache
When this newly created function is called for the first time with a specific set of arguments, the original function is run, and its return value is stored in a cache and returned to the caller of the created function.
The next time the created function is called with the same arguments (as long as the cache is still valid), it will return the cached value instead of re-executing the original function.


<Callout>
`cache` can be defined anywhere and then used inside your components with [`createAsync`](/solid-router/reference/data-apis/create-async).

Expand All @@ -18,8 +17,11 @@ However, using `cache` directly in [`createResource`](/reference/basic-reactivit

```js
const getUser = cache(
(id, options = {}) => fetch(`/api/users/${id}?summary=${options.summary || false}`).then(r => r.json()),
"usersById"
(id, options = {}) =>
fetch(`/api/users/${id}?summary=${options.summary || false}`).then((r) =>
r.json()
),
"usersById"
);

getUser(123); // Causes a GET request to /api/users/123?summary=false
Expand All @@ -28,9 +30,9 @@ getUser(123, { summary: true }); // Causes a GET request to /api/users/123?summa
setTimeout(() => getUser(123, { summary: true }), 999000); // Eventually causes another GET request to /api/users/123?summary=true
```

### With load functions
### With preload functions

Using it with a [load function](https://docs.solidjs.com/solid-router/reference/load-functions/load):
Using it with a [preload function](/solid-router/reference/preload-functions/preload):

```js
import { lazy } from "solid-js";
Expand All @@ -39,13 +41,13 @@ import { getUser } from ... // the cache function

const User = lazy(() => import("./pages/users/[id].js"));

// load function
function loadUser({params, location}) {
// preload function
function preloadUser({params, location}) {
void getUser(params.id)
}

// Pass it in the route definition
<Route path="/users/:id" component={User} load={loadUser} />;
<Route path="/users/:id" component={User} preload={preloadUser} />;
```

### Inside a route's component
Expand All @@ -68,7 +70,7 @@ export default function User(props) {

1. Deduping on the server for the lifetime of the request.
2. Preloading the cache in the browser - this lasts 5 seconds.
When a route is preloaded on hover or when load is called when entering a route it will make sure to dedupe calls.
When a route is preloaded on hover or when preload is called when entering a route it will make sure to dedupe calls.
3. A reactive refetch mechanism based on key.
This prevents routes that are not new from retriggering on action revalidation.
4. Serve as a back/forward cache for browser navigation for up to 5 minutes.
Expand All @@ -77,24 +79,24 @@ export default function User(props) {

## Cache keys

To ensure that the cache keys are consistent and unique, arguments are deterministically serialized using JSON.stringify.
Before serialization, key/value pairs in objects are sorted so that the order of properties does not affect the serialization.
To ensure that the cache keys are consistent and unique, arguments are deterministically serialized using JSON.stringify.
Before serialization, key/value pairs in objects are sorted so that the order of properties does not affect the serialization.
For instance, both `{ name: 'Ryan', awesome: true }` and `{ awesome: true, name: 'Ryan' }` will serialize to the same string so that they produce the same cache key.

## Return value

The return value is a `CachedFunction`, a function that has the same signature as the function you passed to `cache`.
This cached function stores the return value using the cache key.
This cached function stores the return value using the cache key.
Under most circumstances, this temporarily prevents the passed function from running with the same arguments, even if the created function is called repeatedly.

## Arguments

| argument | type | description |
| -------- | ---- | ----------- |
| `fn` | `(...args: any) => any` | A function whose return value you'd like to be cached. |
| `name`* | string | Any arbitrary string that you'd like to use as the rest of the cache key. |
| argument | type | description |
| -------- | ----------------------- | ------------------------------------------------------------------------- |
| `fn` | `(...args: any) => any` | A function whose return value you'd like to be cached. |
| `name`\* | string | Any arbitrary string that you'd like to use as the rest of the cache key. |

*Since the internal cache is shared by all the functions using `cache`, the string should be unique for each function passed to `cache`.
\*Since the internal cache is shared by all the functions using `cache`, the string should be unique for each function passed to `cache`.
If the same key is used with multiple functions, one function might return the cached result of the other.

## Methods
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
title: createAsyncStore
---

Similar to [createAsync](/solid-router/reference/data-apis/create-async) except it uses a deeply reactive store. Perfect for applying fine-grained changes to large model data that updates.

```jsx
const todos = createAsyncStore(() => getTodos());
```
1 change: 1 addition & 0 deletions src/routes/solid-router/reference/data-apis/data.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"action.mdx",
"cache.mdx",
"create-async.mdx",
"create-async-store.mdx",
"response-helpers.mdx"
]
}
2 changes: 1 addition & 1 deletion src/routes/solid-router/reference/data.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{
"title": "Reference",
"pages": ["components", "data-apis", "load-functions", "primitives"]
"pages": ["components", "data-apis", "preload-functions", "primitives"]
}
4 changes: 0 additions & 4 deletions src/routes/solid-router/reference/load-functions/data.json

This file was deleted.

4 changes: 4 additions & 0 deletions src/routes/solid-router/reference/preload-functions/data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"title": "Preload Functions",
"pages": ["preload.mdx"]
}
Original file line number Diff line number Diff line change
@@ -1,26 +1,26 @@
---
title: Load
title: Preload
---

With smart caches waterfalls are still possible with view logic and with lazy loaded code.
With load functions, fetching the data parallel to loading the route is possible to allow use of the data as soon as possible.
The load function can be called when the Route is loaded or eagerly when links are hovered.
With preload functions, fetching the data parallel to loading the route is possible to allow use of the data as soon as possible.
The preload function can be called when the Route is loaded or eagerly when links are hovered.

As its only argument, the load function is passed an object that can used to access route information:
As its only argument, the preload function is passed an object that can used to access route information:

```js
import { lazy } from "solid-js";
import { Route } from "@solidjs/router";

const User = lazy(() => import("./pages/users/[id].js"));

// load function
function loadUser({ params, location }) {
// do loading
// preload function
function preloadUser({ params, location }) {
// do preloading
}

// Pass it in the route definition
<Route path="/users/:id" component={User} load={loadUser} />;
<Route path="/users/:id" component={User} preload={preloadUser} />;
```

| key | type | description |
Expand All @@ -29,18 +29,18 @@ function loadUser({ params, location }) {
| location | `{ pathname, search, hash, query, state, key}` | An object that used to get more information about the path (corresponds to [`useLocation()`](/solid-router/reference/primitives/use-location)) |
| intent | `"initial", "navigate", "native", "preload"` | Indicates why this function is being called. <ul><li>"initial" - the route is being initially shown (ie page load)</li><li>"native" - navigate originated from the browser (eg back/forward)</li><li>"navigate" - navigate originated from the router (eg call to navigate or anchor clicked)</li><li>"preload" - not navigating, just preloading (eg link hover)</li></ul> |

A common pattern is to export the load function and data wrappers that correspond to a route in a dedicated `route.data.js` file.
A common pattern is to export the preload function and data wrappers that correspond to a route in a dedicated `route.data.js` file.
This imports the data functions without loading anything else.

```js
import { lazy } from "solid-js";
import { Route } from "@solidjs/router";
import loadUser from "./pages/users/[id].data.js";
import preloadUser from "./pages/users/[id].data.js";
const User = lazy(() => import("/pages/users/[id].js"));

// In the Route definition
<Route path="/users/:id" component={User} load={loadUser} />;
<Route path="/users/:id" component={User} preload={preloadUser} />;
```

The return value of the `load` function is passed to the page component when called at anytime other than `preload`.
This initializes things in there, or alternatively the following new Data APIs can be used:
The return value of the `preload` function is passed to the page component when called at anytime other than `preload`.
This initializes things in there, or alternatively the following new `Data APIs` can be used.
4 changes: 3 additions & 1 deletion src/routes/solid-router/reference/primitives/data.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
"use-match.mdx",
"use-navigate.mdx",
"use-params.mdx",
"use-search-params.mdx"
"use-search-params.mdx",
"use-current-matches.mdx",
"use-preload-route.mdx"
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
title: useCurrentMatches
---

`useCurrentMatches` returns all the matches for the current matched route. Useful for getting all the route information.

For example if you stored breadcrumbs on your route definition you could retrieve them like so:

```js
const matches = useCurrentMatches();
const breadcrumbs = createMemo(() =>
matches().map((m) => m.route.info.breadcrumb)
);
```
11 changes: 11 additions & 0 deletions src/routes/solid-router/reference/primitives/use-preload-route.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
title: usePreloadRoute
---

`usePreloadRoute` returns a function that can be used to preload a route manually. This is what happens automatically with link hovering and similar focus based behavior, but it is available here as an API.

```js
const preload = usePreloadRoute();

preload(`/users/settings`, { preloadData: true });
```
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export default function Page() {
return (await response.json()) as User[];
});

return <For each={users()}>{(user) => <li>{user.name}</li>}</For>;
return <For each={users()}>{(user) => <li>{user.name}</li>}</For>;
}
```

Expand Down Expand Up @@ -60,7 +60,7 @@ export default function Page() {

With this method, however, there are some caveats to be aware of:

1. The [`load`](/solid-router/reference/load-functions/load) function is called **once** per route, which is the first time the user comes to that route.
1. The [`preload`](/solid-router/reference/preload-functions/preload) function is called **once** per route, which is the first time the user comes to that route.
Following that, the fine-grained resources that remain alive synchronize with state/url changes to refetch data when needed.
If the data needs a refresh, the [`refetch`](/guides/fetching-data#refetch) function returned in the `createResource` can be used.
2. Before the route is rendered, the `load` function is called.
Expand Down
Loading

0 comments on commit 8ada8a7

Please sign in to comment.