# xstate-router

> XState Router. Add routes to your XState machine.

Latest version **0.4.3** (published 2020-03-30) · MIT license · 0 weekly downloads

## Install

```sh
npm install xstate-router
pnpm add xstate-router
yarn add xstate-router
bun add xstate-router
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.4.3 |
| Published | 2020-03-30 |
| First published | 2018-11-26 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 4 |
| Unpacked size | 15.5 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 22 |
| Author | @carloslfu |
| Maintainers | carloslfu |
| Keywords | xstate, react, router, statecharts, state-machines, javascript |

## Links

- npm: https://www.npmjs.com/package/xstate-router
- Repository: https://github.com/carloslfu/xstate-react-router
- Homepage: https://github.com/carloslfu/xstate-react-router#readme
- Issues: https://github.com/carloslfu/xstate-react-router/issues
- npm.io page: https://npm.io/package/xstate-router

## Dependencies (4)

- [history](https://npm.io/package/history.md) ^4.10.1
- [@xstate/graph](https://npm.io/package/@xstate/graph.md) ^1.0.0
- [@xstate/react](https://npm.io/package/@xstate/react.md) ^0.8.1
- [path-to-regexp](https://npm.io/package/path-to-regexp.md) ^6.1.0

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 0.4.3 (latest) — 2020-03-30
- 0.4.2 — 2020-02-19
- 0.4.1 — 2020-02-12
- 0.4.0 — 2020-01-22
- 0.3.1 — 2019-06-04
- 0.3.0 — 2019-06-04
- 0.2.0 — 2019-06-04
- 0.1.1 — 2018-11-26
- 0.1.0 — 2018-11-26

## README

# xstate-router

XState Router. Add routes to your XState machine and maintain it in sync with the actual route.

If you want to use this solution with hooks [use-router-machine](https://github.com/carloslfu/use-router-machine).

## Use

Install the library with `npm i xstate-router`.

If you don't have XState installed, install it: `npm i xstate`

Try the live example here: https://codesandbox.io/s/rllly3pyxp.

The `routerMachine` function returns an interpreter:

```javascript
import { routerMachine } from 'xstate-router'

const machineConfig = {
    initial: 'main',
    context: { myValue: 0 },
    states: {
        main: { meta: { path: '/' } },
        blog: { meta: { path: '/blog' } },
    },
}

const service = routerMachine({
    config: machineConfig,
    options,
    initialContext,
})

// The state changes on a route change and the route changes on a state change.
service.onTransition(state => console.log(state.value))

// The context is enhanced with router properties.
service.onChange(ctx => console.log(ctx))
/* Context
    {
        myValue: 0,
        // Router properties:
        match,
        location,
        history,
    }
*/

```
### Enhanced context

1. *match:*
Tells 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 }`
1. *location:*
The current value of `history.location`
1. *history:*
`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.

if 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:
```javascript
  states: {
      list: { meta: { path: '/items' },
         on: {
            ShowDetails: {
                target: 'details',
                actions: assign((ctx, event) => ({
                                    ...ctx,
                                    match: { id: event.item }
                                }))
            }
         }
      }
      details: { meta: { path: '/items/:id:/details'} }
  }
```
where the event trigger could look like this:
```html
<button onClick={() => this.send('ShowDetails', { item: 817 })}>Show details...</button>
```

### Paths

Paths could have parameters such as `/items/:id:/details` and regular expressions, for more information please read this: https://github.com/pillarjs/path-to-regexp.

### Router events

If a route changes then a parameterized event `'route-changed'` is fired: e.g. `{ dueToStateTransition: "true", route: "/blog", service: /* the xstate interpreter */ }`. 
1. 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`.
1. `route` gives you the current route which causes the event
1. `service` provides the xstate interpreter which can be used to send another event.

Placing 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:
```javascript
  on: {
    'route-changed': {
      cond: (context, event) => event.dueToStateTransition === false
          && !event.processed,            // interfere only new events
      actions: (context, event) => {
        if (context.unsavedData) return;  // suppress current route change
        event.processed = true;           // mark event as processed
        event.service.send(event);        // resend the event to establish the origin route change
      }
    }
  },
```

---
_Source: https://npm.io/package/xstate-router · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
