### Initialize Atomic Router with History
Source: https://atomic-router.github.io/getting-started
This TypeScript example illustrates the complete setup of the Atomic Router. It involves defining an array of routes, creating a history instance (browser or memory), initializing the router with `createHistoryRouter`, and finally attaching the history to the router for navigation management.
```ts
// @/app/routing
import { createHistoryRouter } from 'atomic-router';
import { createBrowserHistory, createMemoryHistory } from 'history';
import { homeRoute } from '@/pages/home';
import { postRoute } from '@/pages/post';
// 1. Define routes
const routes = [
{ path: '/', route: homeRoute },
{ path: '/posts/:postId', route: postRoute },
];
// 2. Create router
const router = createHistoryRouter({
routes: routes,
});
// 3. Create history
const history = isSsr ? createMemoryHistory() : createBrowserHistory();
// 4. Attach it to router
router.setHistory(history);
```
--------------------------------
### Install Atomic Router and Dependencies
Source: https://atomic-router.github.io/getting-started
This command installs the core Atomic Router library along with its essential dependencies, `effector` for state management and `history` for browser history handling. It's the first step to set up a new project using Atomic Router.
```bash
npm install effector atomic-router history
```
--------------------------------
### Atomic Router SolidJS Bindings API
Source: https://atomic-router.github.io/getting-started
This section outlines the API components and utilities provided for integrating Atomic Router with SolidJS applications. These bindings enable SolidJS developers to leverage Atomic Router's routing capabilities seamlessly within their SolidJS projects.
```APIDOC
RouterProvider: A SolidJS Context Provider that makes the router instance available to child components.
createRouteView: A SolidJS utility to render a specific route's content.
createRoutesView: A SolidJS utility to render content based on multiple routes.
Route: A SolidJS component for conditionally rendering content based on the active route.
Link: A SolidJS component for declarative navigation between routes.
```
--------------------------------
### Atomic Router Core API Functions
Source: https://atomic-router.github.io/getting-started
This section lists the core API functions provided by Atomic Router for defining and managing routes and router instances. These functions are fundamental for setting up navigation logic within an application.
```APIDOC
createRoute: Creates an individual route definition.
createHistoryRouter: Initializes the main router instance, typically with a history object.
redirect: A utility function for programmatic redirection.
chainRoute: Chains multiple routes together for sequential processing or conditional routing.
createRouterControls: Provides granular control over router state and navigation.
querySync: Synchronizes query parameters with router state.
```
--------------------------------
### Create Individual Atomic Router Routes
Source: https://atomic-router.github.io/getting-started
This TypeScript snippet demonstrates how to define individual routes using the `createRoute` function from `atomic-router`. It shows examples for a simple home route and a parameterized post route, illustrating how to declare routes that can accept dynamic parameters.
```ts
// @/pages/home
import { createRoute } from 'atomic-router';
export const homeRoute = createRoute();
// @/pages/post
import { createRoute } from 'atomic-router';
export const postRoute = createRoute<{ postId: string }>();
```
--------------------------------
### Configure SWC for Atomic Router `fork` Support
Source: https://atomic-router.github.io/getting-started
This JSON configuration for `.swcrc` enables `fork` support for Atomic Router when using SWC. It requires installing `@effector/swc-plugin` and then adding `"atomic-router"` to the `factories` array within the `plugins` section, ensuring proper integration with the Effector ecosystem.
```json
// .swcrc
{
"$schema": "https://json.schemastore.org/swcrc",
"jsc": {
"experimental": {
"plugins": [
"@effector/swc-plugin",
{
"factories": ["atomic-router"]
}
]
}
}
}
```
--------------------------------
### Atomic Router React Bindings API
Source: https://atomic-router.github.io/getting-started
This section details the API components and hooks available for integrating Atomic Router with React applications. These utilities simplify connecting router logic to React components for rendering routes, creating links, and managing router state within the React ecosystem.
```APIDOC
RouterProvider: A React Context Provider that makes the router instance available to child components.
createRouteView: A higher-order component or hook to render a specific route's content.
createRoutesView: A higher-order component or hook to render content based on multiple routes.
Link: A React component for declarative navigation between routes.
Route: A React component for conditionally rendering content based on the active route.
useLink: A React hook to programmatically get link properties or navigate.
```
--------------------------------
### Configure Babel for Atomic Router `fork` Support
Source: https://atomic-router.github.io/getting-started
This JSON snippet shows the necessary configuration for `.babelrc` to enable `fork` support in Atomic Router. Adding `"atomic-router/babel-preset"` to the presets array ensures that the router's `fork` functionality works correctly within your Babel-transpiled project.
```json
{
"presets": ["atomic-router/babel-preset"]
}
```
--------------------------------
### Atomic Router Data Fetching Setup: Route, Effect, and Store
Source: https://atomic-router.github.io/examples/data-fetching
This snippet initializes the core components for data fetching: a `postRoute` for navigation, a `getPostFx` effect to handle the asynchronous data retrieval (e.g., an API call), and a `$post` store to hold the fetched data, restored from the effect's successful output.
```ts
import { createRoute } from "atomic-router";
import { createEffect, restore } from "effector";
const postRoute = createRoute<{ postId: string }>();
const getPostFx = createEffect((postId: string) => {
return fetch(/* ... */);
});
const $post = restore(getPostFx.doneData, null);
```
--------------------------------
### SolidJS RouterProvider Usage Example
Source: https://atomic-router.github.io/solidjs/api/router-provider
Illustrates the practical application of `RouterProvider` in a SolidJS component. It shows how to initialize a history router and then wrap your application's routes within `RouterProvider`, passing the created router instance as a prop. This setup ensures that routing components like `Route` function correctly.
```tsx
import { createHistoryRouter } from 'atomic-router';
import { RouterProvider, Route } from 'atomic-router-solid';
import { routes } from './routes';
const router = createHistoryRouter({ routes });
export function App() {
return (
);
}
```
--------------------------------
### Install Atomic Router and SolidJS Bindings
Source: https://atomic-router.github.io/solidjs/installation
This `npm add` command installs the core `atomic-router` library and its SolidJS-specific bindings, `atomic-router-solid`, which are essential for integrating Atomic Router with SolidJS applications.
```bash
npm add atomic-router atomic-router-solid
```
--------------------------------
### Install Atomic Router Core and React Bindings
Source: https://atomic-router.github.io/react/installation
This command installs the main Atomic Router package along with its specific bindings for React applications.
```bash
npm add atomic-router atomic-router-react
```
--------------------------------
### Install Atomic Router SolidJS Peer Dependencies
Source: https://atomic-router.github.io/solidjs/installation
This `npm add` command ensures that all necessary peer dependencies for `atomic-router-solid` are installed. These include `effector`, `effector-solid`, and `solid-js`, which are fundamental for the router's functionality within a SolidJS environment.
```bash
npm add effector effector-solid solid-js
```
--------------------------------
### SolidJS Route View Example with Effector Integration
Source: https://atomic-router.github.io/solidjs/api/create-route-view
This example demonstrates how to use `createRouteView` from `atomic-router-solid` within a SolidJS application, integrated with Effector for state management and data fetching. It sets up a route, fetches data before the route opens, and conditionally renders a list of posts or a loading indicator based on the route's status and data availability.
```tsx
import { createRoute } from 'atomic-router';
import { createRouteView } from 'atomic-router-solid';
import { restore, createEffect } from 'effector';
import { useUnit } from 'effector-solid';
import { For } from "solid-js"
const homeRoute = createRoute();
const getPostsFx = createEffect(/* ... */);
const $posts = restore(getPostsFx, []);
const postsLoadedRoute = chainRoute({
route,
beforeOpen: getPostsFx,
});
const PostsList = createRouteView({
route: postsLoadedRoute,
view() {
const posts = useUnit($posts);
return (
{post =>
{post.title}
}
);
},
otherwise() {
return
Loading...
;
},
});
```
--------------------------------
### SolidJS Route Component API and Usage Example
Source: https://atomic-router.github.io/solidjs/api/route
Documents the `Route` component for SolidJS, explaining its purpose to conditionally render a view component when a specified route matches. It includes a comprehensive example demonstrating how to define a route using `createRoute` and then use the `Route` component to link a view to that route.
```APIDOC
Route Component (SolidJS):
Description: Renders a component if the passed route is matched.
Usage:
Parameters:
route: The route object created by `createRoute` (e.g., `homeRoute`).
view: The SolidJS component to render when the route matches (e.g., `HomePage`).
Example:
import { createRoute } from 'atomic-router';
import { Route } from 'atomic-router-solid';
export const homeRoute = createRoute();
function HomePage() {
return
This will render only on home route
;
}
export function App() {
return ;
}
```
--------------------------------
### Basic Link Component Usage Examples (React)
Source: https://atomic-router.github.io/react/api/link
This example showcases various common use cases for the `Link` component. It illustrates how to link to defined internal routes (with and without parameters) and how to create external links, demonstrating the flexibility of the component for navigation.
```tsx
import { createRoute } from 'atomic-router';
import { Link } from 'atomic-router-react';
const homeRoute = createRoute();
const postRoute = createRoute<{ postId: string }>();
function Example() {
return (
Route link
Route link with params
External link
);
}
```
--------------------------------
### Define Atomic Router for Uniswap.org Service
Source: https://atomic-router.github.io/examples/browser-extension
This TypeScript snippet defines a specific router configuration for the `app.uniswap.org` domain using `atomic-router`. It sets up routes for swap and pool creation pages, associating them with their respective paths.
```TypeScript
// @/services/app.uniswap.org
import { createRoute, createHistoryRouter } from 'atomic-router';
import * as routes from './routes';
const domain = 'app.uniswap.org';
const router = createHistoryRouter({
routes: [
{ route: routes.swap, path: '/swap' },
{ route: routes.createPoolFromTo, path: '/add/:from' },
{ route: routes.createPoolFromTo, path: '/add/:from/:to' }
]
});
export const service = { domain, router };
```
--------------------------------
### Chaining Data Loading Effects with Atomic Router `chainRoute`
Source: https://atomic-router.github.io/examples/data-fetching
This example illustrates how to create a loading queue by chaining multiple data fetching effects using Atomic Router's `chainRoute`. It ensures that dependent data (like post, author, and comments) is loaded sequentially, providing fine-grained control over the page's loading states.
```ts
import { createRoute, chainRoute } from "atomic-router";
import { createEffect, restore } from "effector";
export const postRoute = createRoute<{ postId: string }>();
export const getPostFx = createEffect(/* ... */);
export const getAuthorFx = createEffect(/* ... */);
export const getCommentsFx = createEffect(/* ... */);
export const $post = restore(getPostFx, null);
export const $author = restore(getAuthorFx, null);
export const $comments = restore(getCommentsFx, []);
export const postLoadedRoute = chainRoute({
route: postRoute,
beforeOpen: getPostFx,
});
export const authorLoadedRoute = chainRoute({
route: postLoadedRoute,
beforeOpen: {
effect: getUserFx,
source: $post,
mapParams: (_, post) => ({ userId: post.authorId }),
},
});
export const commentsLoadedRoute = chainRoute({
route: postLoadedRoute,
beforeOpen: {
effect: getCommentsFx,
source: $post,
mapParams: (_, post) => ({ postId: post.id }),
},
});
// Post route is opened, nothing loaded
postRoute.$isOpened;
// Only post loaded
postLoadedRoute.$isOpened;
// Author loaded
authorLoadedRoute.$isOpened;
// Comments loaded
commentsLoadedRoute.$isOpened;
```
--------------------------------
### Define Atomic Router for OpenSea.io Service
Source: https://atomic-router.github.io/examples/browser-extension
This TypeScript snippet defines a specific router configuration for the `opensea.io` domain using `atomic-router`. It sets up routes for collection, asset, and creator pages, associating them with their respective paths.
```TypeScript
// @/services/opensea.io
import { createRoute, createHistoryRouter } from 'atomic-router';
import * as routes from './routes';
const domain = 'opensea.io';
const router = createHistoryRouter({
routes: [
{ route: routes.collection, path: '/collection/:collectionId' },
{ route: routes.asset, path: '/assets/:chain/:contractId/:assetId' },
{ route: routes.creator, path: '/:creatorId' }
]
});
export const service = { domain, router };
```
--------------------------------
### Install Atomic Router Peer Dependencies for React
Source: https://atomic-router.github.io/react/installation
This command ensures that all necessary peer dependencies, such as Effector and React, are installed for Atomic Router to function correctly within a React environment.
```bash
npm add effector effector-react react
```
--------------------------------
### Basic Link Usage in SolidJS with Atomic Router
Source: https://atomic-router.github.io/solidjs/api/link
This example demonstrates how to use the `Link` component in a SolidJS application with Atomic Router. It covers linking to defined routes, passing parameters to routes, and creating external links.
```tsx
import { createRoute } from 'atomic-router;
import { Link } from 'atomic-router-solid;
const homeRoute = createRoute<{ postId: string }>();
const postRoute = createRoute<{ postId: string }>();
function Example() {
return (
Route link
Route link with params
External link
);
}
```
--------------------------------
### Applying `chainAuthorized` to an Atomic Router Route
Source: https://atomic-router.github.io/examples/protected-route
Demonstrates how to use the `chainAuthorized` helper to protect an `atomic-router` route. It shows how to create a route and then wrap it with `chainAuthorized` to enforce authorization before the route can be opened.
```ts
import { createRoute } from 'atomic-router';
import { chainAuthorized } from '@/shared/route';
export const editUsersRoute = createRoute();
export const authorizedEditUsersRoute = chainAuthorized(editUsersRoute);
```
--------------------------------
### Conditional Route Opening and Cancellation with `chainRoute` Parameters
Source: https://atomic-router.github.io/examples/data-fetching
This advanced example shows how to use `openOn` and `cancelOn` parameters within `chainRoute` to control when a route is activated or cancelled based on specific conditions. It allows for complex routing logic, such as opening a route only if a post is public and redirecting if it's private or if the request fails.
```ts
import { split, createEffect, restore } from "effector";
import { createRoute, chainRoute, redirect } from "atomic-router";
import { notAllowedRoute } from "@/shared/common-routes";
const postRoute = createRoute<{ postId: string }>();
const getPostFx = createEffect(/* ... */);
// Split request result for public or private posts
const postRequestResult = split(getPostFx.doneData, {
public: (post) => !post.private,
private: (post) => post.private,
});
const $post = restore(postRequestResult.public, null);
// Will open only if post is public
const publicPostLoaded = chainRoute({
route,
beforeOpen: getPostFx,
openOn: postRequestResult.public,
cancelOn: [getPostFx.failData, postRequestResult.private],
});
// Redirect to notAllowedRoute if post is private
redirect({
clock: postRequestResult.private,
route: notAllowedRoute,
});
```
--------------------------------
### Open Catch-All Route with Parameters
Source: https://atomic-router.github.io/examples/catch-all
This TypeScript snippet shows how to programmatically open the previously defined catch-all route (`fooRoute`) by passing an array of path segments to its `open` method. It illustrates that after opening, `fooRoute.$params` will contain the matched segments as an array, reflecting the catch-all behavior.
```TypeScript
fooRoute.open({ param: ['bar', 'baz'] })
```
--------------------------------
### Basic Usage of Atomic Router Route Component in React
Source: https://atomic-router.github.io/react/api/route
Illustrates how to define a route using `createRoute` and render a component conditionally based on route matching using the `Route` component from `atomic-router-react`. This example sets up a basic home route and displays a `HomePage` component when the route matches.
```tsx
import { createRoute } from 'atomic-router;
import { Route } from 'atomic-router-react;
export const homeRoute = createRoute();
function HomePage() {
return
This will render only on home route
;
}
export function App() {
return ;
}
```
--------------------------------
### Combining `chainAuthorized` with Data Fetching in Atomic Router
Source: https://atomic-router.github.io/examples/protected-route
Illustrates how to combine the `chainAuthorized` helper with another `chainRoute` to ensure that a data fetching effect (`getUsersFx`) is triggered only after the user is authorized and the route is opened. This prevents unnecessary data loading for unauthorized users.
```ts
import { createRoute, chainRoute } from 'atomic-router';
import { chainAuthorized } from '@/shared/route';
import { getUsersFx } from './model';
export const editUsersRoute = createRoute();
export const usersLoadedRoute = chainRoute({
route: chainAuthorized(editUsersRoute),
beforeOpen: getUsersFx,
});
```
--------------------------------
### chainRoute with Array of Units for openOn and cancelOn
Source: https://atomic-router.github.io/api/chain-route
This example shows how `beforeOpen`, `openOn`, and `cancelOn` parameters can accept an array of `effector` units (effects or events). This provides flexibility to trigger or cancel route opening based on multiple conditions.
```typescript
const postCommentsLoadedRoute = chainRoute({
route: postRoute,
beforeOpen: getCommentsFx,
openOn: getCommentsFx.doneData,
cancelOn: [getCommentsFx.failData, currentPostDeleted],
});
```
--------------------------------
### Basic `redirect` Usage with Effector Events and Routes
Source: https://atomic-router.github.io/api/redirect
This example illustrates the fundamental usage of the `redirect` operator. It configures a redirect where a `clock` event (e.g., `goHomePressed`) triggers navigation to a specified `route` (e.g., `homeRoute`) without any additional parameters.
```ts
import { createEvent } from 'effector';
import { createRoute, redirect } from 'atomic-router';
const goHomePressed = createEvent();
const homeRoute = createRoute();
redirect({
clock: goHomePressed,
route: homeRoute,
});
```
--------------------------------
### Example Usage of `useLink` Hook in React
Source: https://atomic-router.github.io/react/api/use-link
This example illustrates how to use the `useLink` hook to dynamically generate a URL path from a defined Atomic Router route. It shows how to pass route parameters to the hook to construct the final `href` string, which is useful for creating navigation links.
```tsx
import { useLink } from 'atomic-router-react';
import { createRoute } from 'atomic-router';
// example path: /some/route/:someId
const someRoute = createRoute<{ someId: number }>();
function SomeComponent() {
const path = useLink(someRoute, { someId: 1 });
// -> /some/route/1
}
```
--------------------------------
### Define Catch-All Route with Atomic Router
Source: https://atomic-router.github.io/examples/catch-all
This TypeScript snippet demonstrates how to create a catch-all route using `createRoute` and `createHistoryRouter` from `atomic-router`. It utilizes the `path-to-regexp` library's array parameter feature (`:param+`) to match multiple path segments, such as `/foo/bar` or `/foo/bar/baz`, and store them in an array.
```TypeScript
import { createRoute, createHistoryRouter } from 'atomic-router'
// Create a route with array parameter
const fooRoute = createRoute<{ param: string[] }>()
const router = createHistoryRouter({
routes: [
// Just add "+" sign after `:param` and it works!
{ path: '/foo/:param+', route: fooRoute }
]
})
```
--------------------------------
### Basic Usage of createRoutesView with RouterProvider in React
Source: https://atomic-router.github.io/react/api/create-routes-view
This example illustrates the fundamental usage of `createRoutesView` to render a collection of routes. It shows how to map `RouteInstance` objects to their corresponding React view components and integrates with `RouterProvider` to make the router available throughout the application.
```tsx
import { createRoutesView, RouterProvider } from 'atomic-router-react;
// { route: RouteInstance<...>, view: FC<...> }
import { HomePage } from '@/pages/home';
import { Postpage } from '@/pages/post';
import { router } from '@/app/routing';
const RoutesView = createRoutesView({
routes: [
{ route: HomePage.route, view: HomePage.view },
{ route: HomePage.route, view: PostPage.view },
],
otherwise() {
return
Page not found!
;
},
});
export function App() {
return (
);
}
```
--------------------------------
### Basic Usage of chainRoute with Data Fetching
Source: https://atomic-router.github.io/api/chain-route
This example illustrates how to use `chainRoute` to open a new route (`postLoadedRoute`) only after an asynchronous data fetching operation (`getPostFx`) completes successfully. It uses `effector`'s `createRoute`, `createEffect`, and `restore` to manage the route and its associated data loading.
```typescript
import { createRoute, chainRoute } from 'atomic-router;
import { createEffect, restore } from 'effector;
const postRoute = createRoute<{ postId: string }>();
const getPostFx = createEffect((postId: string) => {
return fetch(/* ... */);
});
const $post = restore(getPostFx.doneData);
const postLoadedRoute = chainRoute({
route: postRoute,
beforeOpen: {
effect: getPostFx,
mapParams: ({ params }) => params.postId,
},
});
```
--------------------------------
### Redirecting with Dynamic Parameters and Query from Effector Stores
Source: https://atomic-router.github.io/api/redirect
This example demonstrates how to use Effector stores (`$post`, `$someQuery`) to provide dynamic parameters and query values for a redirect. When the `clock` event triggers, the current state of the specified stores is used to populate the route's parameters and query.
```ts
import { createRoute, redirect } from 'atomic-router';
import { createStore, createEvent } from 'effector';
const readPostRoute = createRoute<{ postId: string }>();
const readMorePressed = createEvent();
const $post = createStore({ postId: 1 });
redirect({
clock: editPostPressed,
params: $post,
query: $someQuery,
route: editPostRoute,
});
```
--------------------------------
### Initialize Router and History for Browser Extension
Source: https://atomic-router.github.io/examples/browser-extension
This TypeScript snippet demonstrates how to initialize the correct Atomic Router instance based on the current host within a browser extension. It creates a `MemoryHistory` instance to handle URL changes, specifically listening for messages from the background script to update the history, and throws an error if no service is found for the current host.
```TypeScript
// @/app/init.ts
import { createMemoryHistory } from 'history';
import { service as opensea } from '@/services/opensea.io';
import { service as uniswap } from '@/services/app.uniswap.org';
const services = [opensea, uniswap];
// NOTE: Memory history is created instead of regular one
// Because websites usually intercept browser events
function createExtensionHistory() {
const history = createMemoryHistory();
const url = new URL(location.href);
history.push(url.pathname + url.hash + url.search);
chrome.runtime.onMessage.addListener((request) => {
if (request.message === 'url.changed') {
const url = new URL(request.url!);
if (location.host === url.host) {
history.push(url.pathname + url.hash + url.search);
}
}
});
return history;
}
export const initializeRouter = createEffect(() => {
if (!(location.host in services)) {
throw new Error(`Service ${location.host} does not exist`);
n}
const service = services[location.host];
const history = createExtensionHistory();
return service.router.setHistory(history);
});
```
--------------------------------
### Atomic Router Helper for Authorized Route Chaining
Source: https://atomic-router.github.io/examples/protected-route
Implements a `chainAuthorized` helper function that wraps an `atomic-router` route. It uses the `$isAuthorized` store from the auth model to conditionally open the route, ensuring that the route is only activated when the user is authorized or becomes authorized.
```ts
import { chainRoute, RouteParams, RouteInstance, RouteParamsAndQuery } from 'atomic-router';
import { createEvent } from 'effector';
import { $isAuthorized, tokenReceived } from '@/shared/auth';
export function chainAuthorized(route: RouteInstance) {
const sessionCheckStarted = createEvent>();
const alreadyAuthorized = sample({
clock: sessionCheckStarted,
filter: $isAuthorized,
});
return chainRoute({
route,
beforeOpen: sessionCheckStarted,
openOn: [alreadyAuthorized, tokenReceived],
});
}
```
--------------------------------
### Effector Auth Model for Token Management
Source: https://atomic-router.github.io/examples/protected-route
Defines a basic authentication model using Effector, managing user token state and authorization status. It provides events for token reception and erasure, a store for the token, and a derived boolean store indicating if the user is authorized.
```ts
import { createEvent, createStore } from 'effector';
export const tokenReceived = createEvent();
export const tokenErased = createEvent();
export const $token = createStore('');
export const $isAuthorized = $token.map(Boolean);
$token.on(tokenReceived, (prev, token) => token).reset(tokenErased);
```
--------------------------------
### Synchronize Effector Store with Query Parameters (Basic)
Source: https://atomic-router.github.io/api/query-sync
This example demonstrates the basic usage of `querySync` to establish a bidirectional synchronization between an Effector store (`$utmSource`) and a URL query parameter (`utm_source`). It shows how changes in the URL update the store and vice-versa.
```TypeScript
import { createStore } from 'effector';
import { querySync } from 'atomic-router';
import { controls } from '@/shared/routing';
const $utmSource = createStore("");
querySync({
source: { utm_source: $utmSource },
controls,
});
```
--------------------------------
### Handling Data Fetching Errors with Atomic Router `redirect`
Source: https://atomic-router.github.io/examples/data-fetching
This snippet demonstrates how to implement error handling during data fetching by redirecting the user to a different route. It uses Atomic Router's `redirect` function to navigate to a `notFoundRoute` when a data fetching effect, such as `getPostFx`, signals a failure.
```ts
import { redirect } from "atomic-router";
import { notFoundRoute } from "@/shared/common-routes";
redirect({
clock: getPostFx.failData,
route: notFoundRoute,
});
```
--------------------------------
### Atomic Router Data Fetching with chainRoute
Source: https://atomic-router.github.io/examples/data-fetching
This snippet demonstrates how to use `chainRoute` to automatically trigger a data fetching effect (`getPostFx`) whenever `postRoute` is opened or updated. It maps the route parameters to the effect's input and ensures that the `postLoadedRoute` is only opened if the data fetching effect completes successfully and the route is still active.
```ts
import { createRoute, chainRoute } from "atomic-router";
import { createEffect, restore } from "effector";
const postRoute = createRoute<{ postId: string }>();
const getPostFx = createEffect((postId: string) => {
return fetch(/* ... */);
});
const $post = restore(getPostFx.doneData, null);
const postLoadedRoute = chainRoute({
route: postRoute,
beforeOpen: {
effect: getPostFx,
mapParams: ({ params }) => params.postId,
},
});
```
--------------------------------
### Basic Usage of RouterProvider in a React Application
Source: https://atomic-router.github.io/react/api/router-provider
This example illustrates how to wrap your React application with `RouterProvider`, passing a `router` instance created by `createHistoryRouter`. It shows how `Route` components are nested within the provider to define application routes.
```tsx
import { createHistoryRouter } from 'atomic-router';
import { RouterProvider, Route } from 'atomic-router-react';
import { routes } from './routes';
const router = createHistoryRouter({ routes });
const App = () => {
return (
);
};
```
--------------------------------
### Customize Query Parameter Cleanup Strategy
Source: https://atomic-router.github.io/api/query-sync
This example shows how to configure the `cleanup` parameter in `querySync` to control which query parameters are removed from the URL. It demonstrates stripping irrelevant parameters, removing empty ones, and preserving specific parameters like `utm_source`.
```TypeScript
querySync({
source: { q: $q },
cleanup: {
// Strip all params which aren't present in `source`
irrelevant: true,
// Strip empty params ('', 0, false, null)
empty: true,
// Preserves params that should've been removed by irerelevant/empty params
preserve: ['utm_source'],
},
controls,
});
```
--------------------------------
### Displaying Preloaders with Atomic Router and Effector-React
Source: https://atomic-router.github.io/examples/data-fetching
This snippet demonstrates how to conditionally render UI components based on the loading state of a route using `effector-react`'s `useStore` and Atomic Router's `$isOpened` property. It allows displaying a preloader or skeleton while data for a specific route is being fetched.
```tsx
import { useStore } from "effector-react";
import { $post, postLoadedRoute } from "./model";
export const PostPage = () => {
const isPostLoadedRouteOpened = useStore(postLoadedRoute.$isOpened);
if (!isPostLoadedRouteOpened) {
return; /* Loading */
}
return ;
};
const Post = () => {
const post = useStore($post);
return (
{post.title}
{post.text}
);
};
```
--------------------------------
### Handle URL Changes in Browser Extension Background Script
Source: https://atomic-router.github.io/examples/browser-extension
This TypeScript snippet shows how a browser extension's background script listens for tab URL updates. When a URL changes, it sends a message to the content script of the corresponding tab, notifying it about the new URL so the content script can update its internal history.
```TypeScript
// Notify content script about URL changes
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
// read changeInfo data and do something with it
// like send the new url to contentscripts.js
if (changeInfo.url) {
chrome.tabs.sendMessage(tabId, {
message: 'url.changed',
url: changeInfo.url
});
}
});
```
--------------------------------
### Applying Layouts to Routes using createRoutesView
Source: https://atomic-router.github.io/react/api/create-routes-view
Introduced in `atomic-router-react@0.8.0`, this example showcases the use of the optional `layout` prop within the `createRoutesView` configuration. It allows wrapping specific route views with a designated layout component, which helps in avoiding extra re-renders when navigating between pages that share the same layout.
```tsx
const RoutesView = createRoutesView({
routes: [
{ route: Home.route, view: HomePage.view, layout: BaseLayout },
{ route: Posts.route, view: PostsPage.view, layout: BaseLayout },
{ route: SinglePost.route, view: SinglePost.view, layout: SinglePostLayout },
],
otherwise() {
return
Page not found!
;
},
});
```
--------------------------------
### Basic Usage of createHistoryRouter
Source: https://atomic-router.github.io/api/create-router
Illustrates the fundamental steps to set up `createHistoryRouter`, including defining a `routesMap`, creating a router instance, initializing browser or memory history, and attaching the history to the router using `effector`'s `sample`.
```TypeScript
import { sample } from 'effector';
import { createHistoryRouter } from 'atomic-router';
import { createBrowserHistory, createMemoryHistory } from 'history';
import { homeRoute } from '@/pages/home';
import { postsRoute } from '@/pages/posts';
import { postRoute } from '@/pages/post';
import { appStarted } from '@/shared/init';
// 1. Define routes and URLs map
const routesMap = [
{ path: '/', route: homeRoute },
{ path: '/posts', route: postsRoute },
{ path: '/posts/:postId', route: postRoute },
];
// 2. Create router
const router = createHistoryRouter({
routes: routesMap,
});
// 3. Create history
const history = isSSR ? createMemoryHistory() : createBrowserHistory();
// 4. Attach it to router
sample({
clock: appStarted,
fn: () => history,
target: router.setHistory,
})
```
--------------------------------
### Import RouterProvider for SolidJS
Source: https://atomic-router.github.io/solidjs/api/router-provider
Demonstrates how to import the `RouterProvider` component from the `atomic-router-solid` package, which is necessary to make the router instance available throughout your SolidJS application.
```typescript
import { RouterProvider } from 'atomic-router-solid';
```
--------------------------------
### Atomic Router API: createRouterControls
Source: https://atomic-router.github.io/api/create-router-controls
Comprehensive API documentation for `createRouterControls`, detailing its purpose, return values, and how its properties (`$query`, `back`, `forward`) are used to manage router state and navigation externally.
```APIDOC
createRouterControls(): {
$query: StoreWritable;
back: EventCallable;
forward: EventCallable;
}
Purpose:
Creates external router controls to manage navigation and query parameters, solving potential cross-import issues when using `router.back/forward` and enabling features like `querySync`.
Return Value Properties:
- $query: StoreWritable
A writable Effector store containing the current query parameters of the route.
- back: EventCallable
An Effector event that, when triggered, calls `history.back()` to navigate to the previous history entry.
- forward: EventCallable
An Effector event that, when triggered, calls `history.forward()` to navigate to the next history entry.
```
--------------------------------
### Synchronize Query Parameters on a Specific Route
Source: https://atomic-router.github.io/api/query-sync
This example illustrates how to restrict `querySync` functionality to a specific route. By passing a `createRoute()` instance to the `route` parameter, the synchronization of the `$q` store with the `q` query parameter only occurs when `searchRoute` is active.
```TypeScript
import { createStore } from 'effector';
import { createRoute, querySync } from 'atomic-router';
import { controls } from '@/shared/routing';
const searchRoute = createRoute();
const $q = createStore("");
querySync({
source: { q: $q },
route: searchRoute,
controls,
});
```
--------------------------------
### Atomic Router createRoute Methods
Source: https://atomic-router.github.io/api/create-route
This API documentation describes the methods available on a route created with `createRoute`, specifically `.navigate` and `.open`. These methods are used to programmatically trigger navigation to the route, allowing for the inclusion of route parameters, query strings, and history manipulation options.
```APIDOC
createRoute Methods:
.navigate
- Description: Open the route with specified params and query. Can optionally replace the current history entry.
- Signature: Effect & { replace?: boolean }, RouteParamsAndQuery>
- Parameters:
- params: RouteParams - The parameters for the route.
- query: RouteQuery - The query string parameters for the route.
- replace: boolean (optional) - If true, uses `history.replace` instead of `history.push`.
- Example Usage:
sample({
clock: someThingHappened,
fn: () => ({
params: { postId: '123' },
query: { foo: 'bar' },
}),
target: postRoute.navigate,
})
// /posts/:postId -> /posts/123?foo=bar
sample({
clock: someThingHappened,
fn: () => ({
params: { postId: '123' },
query: { foo: 'bar' },
replace: true,
}),
target: postRoute.navigate,
})
.open
- Description: Similar to `.navigate` but only accepts route parameters, without query strings or replace option.
- Signature: Effect>
- Parameters:
- params: RouteParams - The parameters for the route.
- Example Usage:
sample({
clock: somethingHappened,
fn: () => ({ postId: '123' }),
target: postRoute.open,
})
// /posts/:postId -> /posts/123
```
--------------------------------
### Importing createRoutesView for SolidJS
Source: https://atomic-router.github.io/solidjs/api/create-routes-view
Demonstrates the standard import statement for the `createRoutesView` function from the `atomic-router-solid` library, essential for setting up route views in SolidJS applications.
```typescript
import { createRoutesView } from 'atomic-router-solid';
```
--------------------------------
### Initialize Atomic Router Controls
Source: https://atomic-router.github.io/examples/query-params-sync
This snippet shows how to create router controls using `createRouterControls` from `atomic-router`. These controls are essential for managing router state and enabling features like query parameter synchronization across your application.
```typescript
import { createRouterControls} from 'atomic-router'
export const controls = createRouterControls()
```
--------------------------------
### Link Component with All Parameters in SolidJS
Source: https://atomic-router.github.io/solidjs/api/link
This snippet illustrates the comprehensive usage of the `Link` component in SolidJS, showcasing all available parameters including `to` for target, `params` for route parameters, `query` for query string parameters, and `activeClass`/`inactiveClass` for styling based on link activity.
```tsx
import { Link } from 'atomic-router-solid';
export function Example() {
return (
);
}
```
--------------------------------
### Importing createHistoryRouter
Source: https://atomic-router.github.io/api/create-router
Demonstrates how to import the `createHistoryRouter` function from the `atomic-router` library.
```TypeScript
import { createHistoryRouter } from 'atomic-router';
```
--------------------------------
### Synchronize Query Parameters with a Clock Event
Source: https://atomic-router.github.io/api/query-sync
This example demonstrates using the `clock` parameter to control when query parameters are updated. The `$x` and `$y` stores are updated on `canvasDragged`, but the URL's `x` and `y` query parameters are only updated when `canvasDragEnded` is triggered, preventing excessive route updates during continuous dragging.
```TypeScript
import { createRoute, querySync } from 'atomic-router';
import { createStore, createEvent } from 'effector';
import { controls } from '@/shared/routing';
const canvasEditorRoute = createRoute();
const canvasDragged = createEvent();
const canvasDragEnded = createEvent();
const $x = createStore('0');
const $y = createStore('0');
$x.on(canvasDragged, (_, { x }) => x);
$y.on(canvasDragged, (_, { y }) => y);
querySync({
source: { x: $x, y: $y },
route: canvasEditorRoute,
clock: canvasDragEnded,
controls,
});
```
--------------------------------
### Atomic Router: querySync Function API Reference
Source: https://atomic-router.github.io/api/query-sync
Comprehensive API documentation for the `querySync` function, detailing its parameters, their types, and how they influence the synchronization of Effector stores with URL query parameters. It also describes the default and customizable cleanup strategies.
```APIDOC
querySync(config: {
source: Record>;
controls: ReturnType;
route?: Route;
clock?: Event | Effect;
cleanup?: boolean | {
irrelevant?: boolean;
empty?: boolean;
preserve?: string[];
};
})
Description:
Synchronizes chosen Effector stores with query parameters from `createRouterControls`.
Parameters:
- `source`: An object where keys are query parameter names (e.g., 'utm_source') and values are Effector Stores (e.g., `$utmSource`). This defines the bidirectional mapping.
- `controls`: An instance of router controls, typically obtained from `createRouterControls`.
- `route` (optional): A `createRoute()` instance. If provided, the synchronization will only be active when this specific route is matched.
- `clock` (optional): An Effector `Event` or `Effect`. If provided, `querySync` will only update the route's query parameters when this `clock` event is triggered, preventing excessive updates.
- `cleanup` (optional): Defines the strategy for cleaning up query parameters. Defaults to `{ irrelevant: true, empty: false, preserve: [] }`.
- `true`: Shorthand for `{ irrelevant: true, empty: true, preserve: [] }`.
- `false`: Shorthand for `{ irrelevant: false, empty: false, preserve: [] }`.
- `irrelevant` (boolean): If `true`, strips all query parameters that are not present in the `source` object.
- `empty` (boolean): If `true`, strips query parameters whose corresponding store values are considered 'empty' (e.g., `''`, `0`, `false`, `null`).
- `preserve` (string[]): An array of query parameter names to explicitly preserve, even if they would otherwise be removed by `irrelevant` or `empty` rules.
Behavior:
- Updates the specified Effector stores whenever the corresponding query parameters in the URL are updated.
- Updates the URL's query parameters whenever the specified Effector stores are updated.
```
--------------------------------
### Basic Usage of createRoutesView with SolidJS
Source: https://atomic-router.github.io/solidjs/api/create-routes-view
Illustrates the fundamental usage of `createRoutesView` to render a list of routes within a SolidJS application. It shows how to define routes with their corresponding view components and integrate them with the `RouterProvider` to manage application routing.
```tsx
import { createRoutesView, RouterProvider } from 'atomic-router-solid;
// { route: RouteInstance<...>, view: FC<...> }
import { HomePage } from '@/pages/home';
import { Postpage } from '@/pages/post';
import { router } from '@/app/routing';
const RoutesView = createRoutesView({
routes: [
{ route: Home.route, view: HomePage.view },
{ route: Post.route, view: PostPage.view },
],
otherwise() {
return