{"id":13727275,"url":"https://github.com/carloslfu/xstate-router","last_synced_at":"2025-08-15T23:31:03.246Z","repository":{"id":44164007,"uuid":"159118084","full_name":"carloslfu/xstate-router","owner":"carloslfu","description":"XState Router. Add routes to your XState machine.","archived":false,"fork":false,"pushed_at":"2023-01-04T21:39:05.000Z","size":3622,"stargazers_count":112,"open_issues_count":12,"forks_count":16,"subscribers_count":2,"default_branch":"master","last_synced_at":"2024-11-14T17:48:08.001Z","etag":null,"topics":["javascript","react","state-machine","state-management","statecharts","xstate"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/carloslfu.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-11-26T05:55:43.000Z","updated_at":"2024-03-25T04:45:29.000Z","dependencies_parsed_at":"2023-02-02T21:00:37.875Z","dependency_job_id":null,"html_url":"https://github.com/carloslfu/xstate-router","commit_stats":null,"previous_names":[],"tags_count":1,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carloslfu%2Fxstate-router","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carloslfu%2Fxstate-router/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carloslfu%2Fxstate-router/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/carloslfu%2Fxstate-router/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/carloslfu","download_url":"https://codeload.github.com/carloslfu/xstate-router/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":229970361,"owners_count":18152663,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","react","state-machine","state-management","statecharts","xstate"],"created_at":"2024-08-03T01:03:47.492Z","updated_at":"2024-12-16T13:42:59.426Z","avatar_url":"https://github.com/carloslfu.png","language":"TypeScript","funding_links":[],"categories":["TypeScript"],"sub_categories":[],"readme":"# xstate-router\n\nXState Router. Add routes to your XState machine and maintain it in sync with the actual route.\n\n## Use\n\nInstall the library with `npm i xstate-router`.\n\nIf you don't have XState installed, install it: `npm i xstate`\n\nTry the live example here: https://codesandbox.io/s/rllly3pyxp.\n\nThe `routerMachine` function returns an interpreter:\n\n```javascript\nimport { routerMachine } from 'xstate-router'\n\nconst machineConfig = {\n    initial: 'main',\n    context: { myValue: 0 },\n    states: {\n        main: { meta: { path: '/' } },\n        blog: { meta: { path: '/blog' } },\n    },\n}\n\nconst service = routerMachine({\n    config: machineConfig,\n    options,\n    initialContext,\n})\n\n// The state changes on a route change and the route changes on a state change.\nservice.onTransition(state =\u003e console.log(state.value))\n\n// The context is enhanced with router properties.\nservice.onChange(ctx =\u003e console.log(ctx))\n/* Context\n    {\n        myValue: 0,\n        // Router properties:\n        match,\n        location,\n        history,\n    }\n*/\n\n```\n\n### Use with React Hooks\n\n```javascript\nimport { useRouterMachine } from 'xstate-router'\n\nconst config = {\n  initial: 'home',\n  states: {\n    home: { meta: { path: '/' }, on: { NEXT: 'about' } },\n    about: { meta: { path: '/about' }, on: { NEXT: 'dashboard' } },\n    dashboard: {\n      meta: { path: '/dashboard' },\n      initial: 'login',\n      on: { NEXT: 'home' },\n      states: {\n        loggedIn: {\n          initial: 'main',\n          states: {\n            main: { meta: { path: '/dashboard/main' } },\n            data: { meta: { path: '/dashboard/data' } }\n          }\n        },\n        login: {\n          meta: { path: '/dashboard/login' },\n          on: { LoggedIn: 'loggedIn' }\n        }\n      }\n    }\n  }\n}\n\nfunction App() {\n    const service = useRouterMachine({ config })\n\n    return \u003cdiv\u003e{service.state.value}\u003c/div\u003e\n}\n```\n\n### Enhanced context\n\n1. *match:*\nTells you whether the route in the location matches the current state's path. If it matches it contains an object holding properties for each route parameter's value if the path was parameterized. Examples: `null` (not matching), `{}` (no parameters), `{ param1: 4711 }`\n1. *location:*\nThe current value of `history.location`\n1. *history:*\n`routerMachine(...)` accepts a history object as fourth parameter. If it is missing it defaults to `createBrowserHistory()` (from package `'history'`) and is published in the context.\n\nif you translate to a state having a parameterized route then you have to ensure that context.match contains the values of those parameters. Otherwise the placeholder is shown in the route. Example:\n```javascript\n  states: {\n      list: { meta: { path: '/items' },\n         on: {\n            ShowDetails: {\n                target: 'details',\n                actions: assign((ctx, event) =\u003e ({\n                                    ...ctx,\n                                    match: { id: event.item }\n                                }))\n            }\n         }\n      }\n      details: { meta: { path: '/items/:id/details'} }\n  }\n```\nwhere the event trigger could look like this:\n```html\n\u003cbutton onClick={() =\u003e this.send('ShowDetails', { item: 817 })}\u003eShow details...\u003c/button\u003e\n```\n\n### Paths\n\nPaths could have parameters such as `/items/:id/details` and regular expressions, for more information please read this: https://github.com/pillarjs/path-to-regexp.\n\n### Router events\n\nIf a route changes then a parameterized event `'route-changed'` is fired: e.g. `{ dueToStateTransition: \"true\", route: \"/blog\", service: /* the xstate interpreter */ }`. \n1. If the route changes because a state is entered which has a route configured, then `dueToStateTransition` is `true`. If the route changes because the location was changed (either by the user in the browsers location bar or by a script changing `history.location`), then `dueToStateTransition` is `false`.\n1. `route` gives you the current route which causes the event\n1. `service` provides the xstate interpreter which can be used to send another event.\n\nPlacing an `on: 'router-changed'` event at a state can be used to avoid leaving the current state if the route changes. Think of a state which might show unsaved data and you want to ask the user *'Leave and loose unsaved data?'*. If you decide to accept the new route anyway you have to resend the event:\n```javascript\n  on: {\n    'route-changed': {\n      cond: (context, event) =\u003e event.dueToStateTransition === false\n          \u0026\u0026 !event.processed,            // interfere only new events\n      actions: (context, event) =\u003e {\n        if (context.unsavedData) return;  // suppress current route change\n        event.processed = true;           // mark event as processed\n        event.service.send(event);        // resend the event to establish the origin route change\n      }\n    }\n  },\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcarloslfu%2Fxstate-router","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcarloslfu%2Fxstate-router","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcarloslfu%2Fxstate-router/lists"}