The main purpose of this project is make it easy to use XState machines and create global state with it. Since XState don't have yet this feature, Storz will help you with this job.
- πΒ Features
- π¦Β Install
- π§π»βπ»Β Usage
- πΒ Example
- πͺπ»Β Contributing
- πΒ License
- β Handle global machines easily
- β
Frameworkless library on
@storz/core
- β
React integration with
@storz/react
- β No external libs, just XState
$ yarn add @storz/react
$ pnpm install @storz/react
- First create you global store with your actions as parameters:
import { createStore } from '@storz/react';
import { testMachine } from './testMachine';
export const store = create({
test: testMachine,
});
- Then, just use your machine anywhere in your application
import { store } from './store';
export function MyComponent() {
const value = store.useSelector('count', (s) => s.context.value);
return <div>{value}</div>;
}
One of the main problem when using a global state machine is in the case you need to define some actions that depends on be in the context of React. To cover that, with Storz you can use useSetMachineConfig
and handle you configurations easily:
import { useState } from 'react';
import { store } from './store';
function DoubleCounter() {
const [double, setDouble] = useState(0);
store.useSetMachineConfig('counter', {
actions: {
setDoubleExternally(ctx) {
setDouble(ctx.value * 2);
},
},
});
return <div>{double}</div>;
}
You can define events inside your store in order to create automatic handlers you can access anywhere also in your code:
import { createStore } from '@storz/react';
import { testMachine } from './testMachine';
export const store = create(
{ test: testMachine },
{
events: (store) => ({
someEvent: () => store.send('test', { type: 'MY_EVENT ' }),
}),
}
);
store.someEvent(); // this method now is attached to your store
Check our basic example in order to see the app up and running. But basically that's what you'll find there:
import { createStore } from '@storz/react';
import { counterMachine } from './counterMachine';
const events = (store) => ({
increment() {
store.send('counter', { type: 'INCREMENT' });
},
decrement() {
store.send('counter', { type: 'DECREMENT' });
},
});
export const store = createStore({ counter: counterMachine }, { events });
function Increment() {
return <button onClick={store.increment}>Inc</button>;
}
function Decrement() {
return <button onClick={store.decrement}>Inc</button>;
}
function Counter() {
const value = store.useSelector('counter', (s) => s.context.value);
return <div>{value}</div>;
}
export function App() {
return (
<div>
<Increment />
<Decrement />
<Counter />
</div>
);
}
Feel like contributing? That's awesome! We have a contributing guide to help guide you.
The primary license for this repo is MIT
, see LICENSE
.