Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[@xstate/store] Add examples + update createStoreWithProducer(…) #5079

Merged
merged 19 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion examples/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ These steps assume You've forked the repo and created a branch for your PR. For

```bash
pnpm create vite@latest my-example-react --template react-ts
cd my-example-react
```

2. Install `xstate` and the library-specific beta (e.g. `@xstate/react`):

```bash
pnpm i xstate @xstate/react
pnpm install xstate @xstate/react
```

3. Add your XState-powered demo code ✨
Expand Down
36 changes: 20 additions & 16 deletions packages/xstate-store/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ npm install @xstate/store
```ts
import { createStore } from '@xstate/store';

export const donutStore = createStore(
{ donuts: 0, favoriteFlavor: 'chocolate' },

{
export const donutStore = createStore({
context: {
donuts: 0,
favoriteFlavor: 'chocolate'
},
on: {
addDonut: {
donuts: (context) => context.donuts + 1
},
Expand All @@ -37,7 +39,7 @@ export const donutStore = createStore(
donuts: 0
}
}
);
});

donutStore.subscribe((snapshot) => {
console.log(snapshot.context);
Expand Down Expand Up @@ -103,13 +105,12 @@ XState Store makes it really easy to integrate with immutable update libraries l
import { createStoreWithProducer } from '@xstate/store';
import { produce } from 'immer'; // or { create } from 'mutative'

const donutStore = createStoreWithProducer(
produce,
{
const donutStore = createStoreWithProducer(produce, {
context: {
donuts: 0,
favoriteFlavor: 'chocolate'
},
{
on: {
addDonut: (context) => {
context.donuts++; // "Mutation" (thanks to the producer)
},
Expand All @@ -120,7 +121,7 @@ const donutStore = createStoreWithProducer(
context.donuts = 0;
}
}
);
});

// Everything else is the same!
```
Expand All @@ -132,17 +133,17 @@ XState Store is written in TypeScript and provides full type safety, _without_ y
```ts
import { createStore } from '@xstate/store';

const donutStore = createStore(
// Inferred as:
const donutStore = createStore({
// Context inferred as:
// {
// donuts: number;
// favoriteFlavor: string;
// }
{
context: {
donuts: 0,
favoriteFlavor: 'chocolate'
},
{
on: {
// Event inferred as:
// {
// type: 'changeFlavor';
Expand All @@ -152,7 +153,7 @@ const donutStore = createStore(
context.favoriteFlavor = event.flavor;
}
}
);
});

donutStore.getSnapshot().context.favoriteFlavor; // string

Expand All @@ -178,6 +179,9 @@ const donutContext: DonutContext = {
};

const donutStore = createStore(donutContext, {
// ... (transitions go here)
context: donutContext,
on: {
// ... (transitions go here)
}
});
```
24 changes: 24 additions & 0 deletions packages/xstate-store/examples/counter-react/.gitignore
davidkpiano marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
50 changes: 50 additions & 0 deletions packages/xstate-store/examples/counter-react/README.md
davidkpiano marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# React + TypeScript + Vite

This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.

Currently, two official plugins are available:

- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh

## Expanding the ESLint configuration

If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:

- Configure the top-level `parserOptions` property like this:

```js
export default tseslint.config({
languageOptions: {
// other options...
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname
}
}
});
```

- Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked`
- Optionally add `...tseslint.configs.stylisticTypeChecked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config:

```js
// eslint.config.js
import react from 'eslint-plugin-react';

export default tseslint.config({
// Set the react version
settings: { react: { version: '18.3' } },
plugins: {
// Add the react plugin
react
},
rules: {
// other rules...
// Enable its recommended rules
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules
}
});
```
28 changes: 28 additions & 0 deletions packages/xstate-store/examples/counter-react/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import js from '@eslint/js';
import globals from 'globals';
import reactHooks from 'eslint-plugin-react-hooks';
import reactRefresh from 'eslint-plugin-react-refresh';
import tseslint from 'typescript-eslint';

export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true }
]
}
}
);
13 changes: 13 additions & 0 deletions packages/xstate-store/examples/counter-react/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
30 changes: 30 additions & 0 deletions packages/xstate-store/examples/counter-react/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "counter-react",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@xstate/store": "^2.4.0",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
"@types/react": "^18.3.3",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.1",
"eslint": "^9.9.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9",
"globals": "^15.9.0",
"typescript": "^5.5.3",
"typescript-eslint": "^8.0.1",
"vite": "^5.4.1"
}
}
42 changes: 42 additions & 0 deletions packages/xstate-store/examples/counter-react/src/App.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}

.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}

@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}

@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}

.card {
padding: 2em;
}

.read-the-docs {
color: #888;
}
60 changes: 60 additions & 0 deletions packages/xstate-store/examples/counter-react/src/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import './App.css';
import { createStore } from '@xstate/store';

Check failure on line 2 in packages/xstate-store/examples/counter-react/src/App.tsx

View workflow job for this annotation

GitHub Actions / build

Cannot find module '@xstate/store' or its corresponding type declarations.
import { useSelector } from '@xstate/store/react';

Check failure on line 3 in packages/xstate-store/examples/counter-react/src/App.tsx

View workflow job for this annotation

GitHub Actions / build

Cannot find module '@xstate/store/react' or its corresponding type declarations.
import { useEffect } from 'react';
import { createBrowserInspector } from '@statelyai/inspect';

Check failure on line 5 in packages/xstate-store/examples/counter-react/src/App.tsx

View workflow job for this annotation

GitHub Actions / build

Cannot find module '@statelyai/inspect' or its corresponding type declarations.
davidkpiano marked this conversation as resolved.
Show resolved Hide resolved

const inspector = createBrowserInspector();

const store = createStore({
context: {
count: 0
},
on: {
inc: (context, event: { by: number }) => {

Check failure on line 14 in packages/xstate-store/examples/counter-react/src/App.tsx

View workflow job for this annotation

GitHub Actions / build

Parameter 'context' implicitly has an 'any' type.
return {
count: context.count + event.by
};
},
reset: (_context, _ev, { emit }) => {

Check failure on line 19 in packages/xstate-store/examples/counter-react/src/App.tsx

View workflow job for this annotation

GitHub Actions / build

Parameter '_context' implicitly has an 'any' type.

Check failure on line 19 in packages/xstate-store/examples/counter-react/src/App.tsx

View workflow job for this annotation

GitHub Actions / build

Parameter '_ev' implicitly has an 'any' type.

Check failure on line 19 in packages/xstate-store/examples/counter-react/src/App.tsx

View workflow job for this annotation

GitHub Actions / build

Binding element 'emit' implicitly has an 'any' type.
emit({ type: 'reset' });
return {
count: 0
};
}
}
});

store.inspect(inspector.inspect);

function App() {
const count = useSelector(store, (s) => s.context.count);

Check failure on line 31 in packages/xstate-store/examples/counter-react/src/App.tsx

View workflow job for this annotation

GitHub Actions / build

Parameter 's' implicitly has an 'any' type.

useEffect(() => {
const sub = store.on('reset', () => {
console.log('Count reset!');
});

return sub.unsubscribe;
}, []);

return (
<>
<div
className="card"
style={{
display: 'flex',
flexDirection: 'row',
gap: '.5rem'
}}
>
<button onClick={() => store.send({ type: 'inc', by: 1 })}>
count is {count}
</button>
<button onClick={() => store.send({ type: 'reset' })}>reset</button>
</div>
</>
);
}

export default App;
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading