@xstate/react 1.6.1 → 2.0.0-pr2674-2021926101023

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,58 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.0.0-pr2674-2021926101023
4
+
5
+ ### Major Changes
6
+
7
+ - e5a8b8dff: author: @Andarist
8
+ author: @mattpocock
9
+
10
+ To avoid breaking any consumers and to leverage the newly introduced typegen support the major version of this package had to be bumped. While you can still use it with older versions of TS the typegen support in this package required at least TS 4.0.
11
+
12
+ ### Patch Changes
13
+
14
+ - Updated dependencies [1cd26811c]
15
+ - xstate@4.27.0-pr2674-2021926101023
16
+
17
+ ## 1.6.2
18
+
19
+ ### Patch Changes
20
+
21
+ - [#2736](https://github.com/statelyai/xstate/pull/2736) [`2246ae051`](https://github.com/statelyai/xstate/commit/2246ae051663f261b4750d7adba57f008ec28f1d) Thanks [@Andarist](https://github.com/Andarist), [@davidkpiano](https://github.com/davidkpiano), [@VanTanev](https://github.com/VanTanev)! - The `useSelector(...)` hook now works as expected when the `actor` passed in changes. The hook will properly subscribe to the new `actor` and select the desired value. See [#2702](https://github.com/statelyai/xstate/issues/2702)
22
+
23
+ * [#2685](https://github.com/statelyai/xstate/pull/2685) [`469268d39`](https://github.com/statelyai/xstate/commit/469268d39fbc23996599773adfc4ca824b48585f) Thanks [@farskid](https://github.com/farskid), [@Andarist](https://github.com/Andarist)! - Fixed a regression with a development-only warning not being shown when a machine reference is updated during the hook lifecycle. This usually happens when machine options are dependent on external values and they're passed via `withConfig`.
24
+
25
+ ```js
26
+ const machine = createMachine({
27
+ initial: 'foo',
28
+ context: { id: 1 },
29
+ states: {
30
+ foo: {
31
+ on: {
32
+ CHECK: {
33
+ target: 'bar',
34
+ cond: 'hasOverflown'
35
+ }
36
+ }
37
+ },
38
+ bar: {}
39
+ }
40
+ });
41
+
42
+ const [id, setId] = useState(1);
43
+ const [current, send] = useMachine(
44
+ machine.withConfig({
45
+ guards: {
46
+ hasOverflown: () => id > 1 // id is a reference to an outside value
47
+ }
48
+ })
49
+ );
50
+
51
+ // later when id updates
52
+ setId(2);
53
+ // Now the reference passed to `useMachine` (the result of `machine.withConfig`) is updated but the interpreted machine stays the same. So the guard is still the previous one that got passed to the `useMachine` initially, and it closes over the stale `id`.
54
+ ```
55
+
3
56
  ## 1.6.1
4
57
 
5
58
  ### Patch Changes
package/README.md CHANGED
@@ -1,8 +1,11 @@
1
1
  # @xstate/react
2
2
 
3
- [[toc]]
3
+ This package contains utilities for using [XState](https://github.com/statelyai/xstate) with [React](https://github.com/facebook/react/).
4
4
 
5
- ## Quick Start
5
+ - [Read the full documentation in the XState docs](https://xstate.js.org/docs/packages/xstate-react/).
6
+ - [Read our contribution guidelines](https://github.com/statelyai/xstate/blob/main/CONTRIBUTING.md).
7
+
8
+ ## Quick start
6
9
 
7
10
  1. Install `xstate` and `@xstate/react`:
8
11
 
@@ -57,513 +60,3 @@ export const Toggler = () => {
57
60
  );
58
61
  };
59
62
  ```
60
-
61
- ## Examples
62
-
63
- - [XState + React TodoMVC (CodeSandbox)](https://codesandbox.io/s/xstate-todomvc-33wr94qv1)
64
-
65
- ## API
66
-
67
- ### `useMachine(machine, options?)`
68
-
69
- A [React hook](https://reactjs.org/hooks) that interprets the given `machine` and starts a service that runs for the lifetime of the component.
70
-
71
- **Arguments**
72
-
73
- - `machine` - An [XState machine](https://xstate.js.org/docs/guides/machines.html) or a function that lazily returns a machine:
74
-
75
- ```js
76
- // existing machine
77
- const [state, send] = useMachine(machine);
78
-
79
- // lazily-created machine
80
- const [state, send] = useMachine(() =>
81
- createMachine({
82
- /* ... */
83
- })
84
- );
85
- ```
86
-
87
- - `options` (optional) - [Interpreter options](https://xstate.js.org/docs/guides/interpretation.html#options) and/or any of the following machine config options: `guards`, `actions`, `services`, `delays`, `immediate`, `context`, `state`.
88
-
89
- **Returns** a tuple of `[state, send, service]`:
90
-
91
- - `state` - Represents the current state of the machine as an XState `State` object.
92
- - `send` - A function that sends events to the running service.
93
- - `service` - The created service.
94
-
95
- ### `useService(service)`
96
-
97
- ::: warning Deprecated
98
-
99
- In the next major version, `useService(service)` will be replaced with `useActor(service)`. Prefer using the `useActor(service)` hook for services instead, since services are also actors.
100
-
101
- Also, keep in mind that only a single argument (the event object) can be sent to `send(eventObject)` from `useActor(...)`. When migrating to `useActor(...)`, refactor `send(...)` calls to use only a single event object:
102
-
103
- ```diff
104
- const [state, send] = useActor(service);
105
- -send('CLICK', { x: 0, y: 3 });
106
- +send({ type: 'CLICK', x: 0, y: 3 });
107
- ```
108
-
109
- :::
110
-
111
- A [React hook](https://reactjs.org/hooks) that subscribes to state changes from an existing [service](https://xstate.js.org/docs/guides/interpretation.html).
112
-
113
- **Arguments**
114
-
115
- - `service` - An [XState service](https://xstate.js.org/docs/guides/interpretation.html).
116
-
117
- **Returns** a tuple of `[state, send]`:
118
-
119
- - `state` - Represents the current state of the service as an XState `State` object.
120
- - `send` - A function that sends events to the running service.
121
-
122
- ### `useActor(actor, getSnapshot?)`
123
-
124
- A [React hook](https://reactjs.org/hooks) that subscribes to emitted changes from an existing [actor](https://xstate.js.org/docs/guides/actors.html).
125
-
126
- **Arguments**
127
-
128
- - `actor` - an actor-like object that contains `.send(...)` and `.subscribe(...)` methods.
129
- - `getSnapshot` - a function that should return the latest emitted value from the `actor`.
130
- - Defaults to attempting to get the `actor.state`, or returning `undefined` if that does not exist.
131
-
132
- ```js
133
- const [state, send] = useActor(someSpawnedActor);
134
-
135
- // with custom actors
136
- const [state, send] = useActor(customActor, (actor) => {
137
- // implementation-specific pseudocode example:
138
- return actor.getLastEmittedValue();
139
- });
140
- ```
141
-
142
- ### `useInterpret(machine, options?, observer?)`
143
-
144
- A React hook that returns the `service` created from the `machine` with the `options`, if specified. It also sets up a subscription to the `service` with the `observer`, if provided.
145
-
146
- _Since 1.3.0_
147
-
148
- **Arguments**
149
-
150
- - `machine` - An [XState machine](https://xstate.js.org/docs/guides/machines.html) or a function that lazily returns a machine.
151
- - `options` (optional) - [Interpreter options](https://xstate.js.org/docs/guides/interpretation.html#options) and/or any of the following machine config options: `guards`, `actions`, `services`, `delays`, `immediate`, `context`, `state`.
152
- - `observer` (optional) - an observer or listener that listens to state updates:
153
- - an observer (e.g., `{ next: (state) => {/* ... */} }`)
154
- - or a listener (e.g., `(state) => {/* ... */}`)
155
-
156
- ```js
157
- import { useInterpret } from '@xstate/react';
158
- import { someMachine } from '../path/to/someMachine';
159
-
160
- const App = () => {
161
- const service = useInterpret(someMachine);
162
-
163
- // ...
164
- };
165
- ```
166
-
167
- With options + listener:
168
-
169
- ```js
170
- // ...
171
-
172
- const App = () => {
173
- const service = useInterpret(
174
- someMachine,
175
- {
176
- actions: {
177
- /* ... */
178
- }
179
- },
180
- (state) => {
181
- // subscribes to state changes
182
- console.log(state);
183
- }
184
- );
185
-
186
- // ...
187
- };
188
- ```
189
-
190
- ### `useSelector(actor, selector, compare?, getSnapshot?)`
191
-
192
- A React hook that returns the selected value from the snapshot of an `actor`, such as a service. This hook will only cause a rerender if the selected value changes, as determined by the optional `compare` function.
193
-
194
- _Since 1.3.0_
195
-
196
- **Arguments**
197
-
198
- - `actor` - a service or an actor-like object that contains `.send(...)` and `.subscribe(...)` methods.
199
- - `selector` - a function that takes in an actor's "current state" (snapshot) as an argument and returns the desired selected value.
200
- - `compare` (optional) - a function that determines if the current selected value is the same as the previous selected value.
201
- - `getSnapshot` (optional) - a function that should return the latest emitted value from the `actor`.
202
- - Defaults to attempting to get the `actor.state`, or returning `undefined` if that does not exist. Will automatically pull the state from services.
203
-
204
- ```js
205
- import { useSelector } from '@xstate/react';
206
-
207
- // tip: optimize selectors by defining them externally when possible
208
- const selectCount = (state) => state.context.count;
209
-
210
- const App = ({ service }) => {
211
- const count = useSelector(service, selectCount);
212
-
213
- // ...
214
- };
215
- ```
216
-
217
- With `compare` function:
218
-
219
- ```js
220
- // ...
221
-
222
- const selectUser = (state) => state.context.user;
223
- const compareUser = (prevUser, nextUser) => prevUser.id === nextUser.id;
224
-
225
- const App = ({ service }) => {
226
- const user = useSelector(service, selectUser, compareUser);
227
-
228
- // ...
229
- };
230
- ```
231
-
232
- With `useInterpret(...)`:
233
-
234
- ```js
235
- import { useInterpret, useSelector } from '@xstate/react';
236
- import { someMachine } from '../path/to/someMachine';
237
-
238
- const selectCount = (state) => state.context.count;
239
-
240
- const App = ({ service }) => {
241
- const service = useInterpret(someMachine);
242
- const count = useSelector(service, selectCount);
243
-
244
- // ...
245
- };
246
- ```
247
-
248
- ### `asEffect(action)`
249
-
250
- Ensures that the `action` is executed as an effect in `useEffect`, rather than being immediately executed.
251
-
252
- **Arguments**
253
-
254
- - `action` - An action function (e.g., `(context, event) => { alert(context.message) })`)
255
-
256
- **Returns** a special action function that wraps the original so that `useMachine` knows to execute it in `useEffect`.
257
-
258
- **Example**
259
-
260
- ```jsx
261
- const machine = createMachine({
262
- initial: 'focused',
263
- states: {
264
- focused: {
265
- entry: 'focus'
266
- }
267
- }
268
- });
269
-
270
- const Input = () => {
271
- const inputRef = useRef(null);
272
- const [state, send] = useMachine(machine, {
273
- actions: {
274
- focus: asEffect((context, event) => {
275
- inputRef.current && inputRef.current.focus();
276
- })
277
- }
278
- });
279
-
280
- return <input ref={inputRef} />;
281
- };
282
- ```
283
-
284
- ### `asLayoutEffect(action)`
285
-
286
- Ensures that the `action` is executed as an effect in `useLayoutEffect`, rather than being immediately executed.
287
-
288
- **Arguments**
289
-
290
- - `action` - An action function (e.g., `(context, event) => { alert(context.message) })`)
291
-
292
- **Returns** a special action function that wraps the original so that `useMachine` knows to execute it in `useLayoutEffect`.
293
-
294
- ### `useMachine(machine)` with `@xstate/fsm`
295
-
296
- A [React hook](https://reactjs.org/hooks) that interprets the given finite state `machine` from [`@xstate/fsm`] and starts a service that runs for the lifetime of the component.
297
-
298
- This special `useMachine` hook is imported from `@xstate/react/fsm`
299
-
300
- **Arguments**
301
-
302
- - `machine` - An [XState finite state machine (FSM)](https://xstate.js.org/docs/packages/xstate-fsm/).
303
- - `options` - An optional `options` object.
304
-
305
- **Returns** a tuple of `[state, send, service]`:
306
-
307
- - `state` - Represents the current state of the machine as an `@xstate/fsm` `StateMachine.State` object.
308
- - `send` - A function that sends events to the running service.
309
- - `service` - The created `@xstate/fsm` service.
310
-
311
- **Example**
312
-
313
- ```js
314
- import { useEffect } from 'react';
315
- import { useMachine } from '@xstate/react/fsm';
316
- import { createMachine } from '@xstate/fsm';
317
-
318
- const context = {
319
- data: undefined
320
- };
321
- const fetchMachine = createMachine({
322
- id: 'fetch',
323
- initial: 'idle',
324
- context,
325
- states: {
326
- idle: {
327
- on: { FETCH: 'loading' }
328
- },
329
- loading: {
330
- entry: ['load'],
331
- on: {
332
- RESOLVE: {
333
- target: 'success',
334
- actions: assign({
335
- data: (context, event) => event.data
336
- })
337
- }
338
- }
339
- },
340
- success: {}
341
- }
342
- });
343
-
344
- const Fetcher = ({
345
- onFetch = () => new Promise((res) => res('some data'))
346
- }) => {
347
- const [state, send] = useMachine(fetchMachine, {
348
- actions: {
349
- load: () => {
350
- onFetch().then((res) => {
351
- send({ type: 'RESOLVE', data: res });
352
- });
353
- }
354
- }
355
- });
356
-
357
- switch (state.value) {
358
- case 'idle':
359
- return <button onClick={(_) => send('FETCH')}>Fetch</button>;
360
- case 'loading':
361
- return <div>Loading...</div>;
362
- case 'success':
363
- return (
364
- <div>
365
- Success! Data: <div data-testid="data">{state.context.data}</div>
366
- </div>
367
- );
368
- default:
369
- return null;
370
- }
371
- };
372
- ```
373
-
374
- ## Configuring Machines
375
-
376
- Existing machines can be configured by passing the machine options as the 2nd argument of `useMachine(machine, options)`.
377
-
378
- Example: the `'fetchData'` service and `'notifySuccess'` action are both configurable:
379
-
380
- ```js
381
- const fetchMachine = createMachine({
382
- id: 'fetch',
383
- initial: 'idle',
384
- context: {
385
- data: undefined,
386
- error: undefined
387
- },
388
- states: {
389
- idle: {
390
- on: { FETCH: 'loading' }
391
- },
392
- loading: {
393
- invoke: {
394
- src: 'fetchData',
395
- onDone: {
396
- target: 'success',
397
- actions: assign({
398
- data: (_, event) => event.data
399
- })
400
- },
401
- onError: {
402
- target: 'failure',
403
- actions: assign({
404
- error: (_, event) => event.data
405
- })
406
- }
407
- }
408
- },
409
- success: {
410
- entry: 'notifySuccess',
411
- type: 'final'
412
- },
413
- failure: {
414
- on: {
415
- RETRY: 'loading'
416
- }
417
- }
418
- }
419
- });
420
-
421
- const Fetcher = ({ onResolve }) => {
422
- const [state, send] = useMachine(fetchMachine, {
423
- actions: {
424
- notifySuccess: (ctx) => onResolve(ctx.data)
425
- },
426
- services: {
427
- fetchData: (_, e) =>
428
- fetch(`some/api/${e.query}`).then((res) => res.json())
429
- }
430
- });
431
-
432
- switch (state.value) {
433
- case 'idle':
434
- return (
435
- <button onClick={() => send('FETCH', { query: 'something' })}>
436
- Search for something
437
- </button>
438
- );
439
- case 'loading':
440
- return <div>Searching...</div>;
441
- case 'success':
442
- return <div>Success! Data: {state.context.data}</div>;
443
- case 'failure':
444
- return (
445
- <>
446
- <p>{state.context.error.message}</p>
447
- <button onClick={() => send('RETRY')}>Retry</button>
448
- </>
449
- );
450
- default:
451
- return null;
452
- }
453
- };
454
- ```
455
-
456
- ## Matching States
457
-
458
- When using [hierarchical](https://xstate.js.org/docs/guides/hierarchical.html) and [parallel](https://xstate.js.org/docs/guides/parallel.html) machines, the state values will be objects, not strings. In this case, it is best to use [`state.matches(...)`](https://xstate.js.org/docs/guides/states.html#state-methods-and-getters).
459
-
460
- We can do this with `if/else if/else` blocks:
461
-
462
- ```js
463
- // ...
464
- if (state.matches('idle')) {
465
- return /* ... */;
466
- } else if (state.matches({ loading: 'user' })) {
467
- return /* ... */;
468
- } else if (state.matches({ loading: 'friends' })) {
469
- return /* ... */;
470
- } else {
471
- return null;
472
- }
473
- ```
474
-
475
- We can also continue to use `switch`, but we must make an adjustment to our approach. By setting the expression of the `switch` to `true`, we can use [`state.matches(...)`](https://xstate.js.org/docs/guides/states.html#state-methods-and-getters) as a predicate in each `case`:
476
-
477
- ```js
478
- switch (true) {
479
- case state.matches('idle'):
480
- return /* ... */;
481
- case state.matches({ loading: 'user' }):
482
- return /* ... */;
483
- case state.matches({ loading: 'friends' }):
484
- return /* ... */;
485
- default:
486
- return null;
487
- }
488
- ```
489
-
490
- A ternary statement can also be considered, especially within rendered JSX:
491
-
492
- ```jsx
493
- const Loader = () => {
494
- const [state, send] = useMachine(/* ... */);
495
-
496
- return (
497
- <div>
498
- {state.matches('idle') ? (
499
- <Loader.Idle />
500
- ) : state.matches({ loading: 'user' }) ? (
501
- <Loader.LoadingUser />
502
- ) : state.matches({ loading: 'friends' }) ? (
503
- <Loader.LoadingFriends />
504
- ) : null}
505
- </div>
506
- );
507
- };
508
- ```
509
-
510
- ## Persisted and Rehydrated State
511
-
512
- You can persist and rehydrate state with `useMachine(...)` via `options.state`:
513
-
514
- ```js
515
- // ...
516
-
517
- // Get the persisted state config object from somewhere, e.g. localStorage
518
- const persistedState = JSON.parse(localStorage.getItem('some-persisted-state-key')) || someMachine.initialState;
519
-
520
- const App = () => {
521
- const [state, send] = useMachine(someMachine, {
522
- state: persistedState // provide persisted state config object here
523
- });
524
-
525
- // state will initially be that persisted state, not the machine's initialState
526
-
527
- return (/* ... */)
528
- }
529
- ```
530
-
531
- ## Services
532
-
533
- The `service` created in `useMachine(machine)` can be referenced as the third returned value:
534
-
535
- ```js
536
- // vvvvvvv
537
- const [state, send, service] = useMachine(someMachine);
538
- ```
539
-
540
- You can subscribe to that service's state changes with the [`useEffect` hook](https://reactjs.org/docs/hooks-effect.html):
541
-
542
- ```js
543
- // ...
544
-
545
- useEffect(() => {
546
- const subscription = service.subscribe((state) => {
547
- // simple state logging
548
- console.log(state);
549
- });
550
-
551
- return subscription.unsubscribe;
552
- }, [service]); // note: service should never change
553
- ```
554
-
555
- ## Migration from 0.x
556
-
557
- - For spawned actors created using `invoke` or `spawn(...)`, use the `useActor()` hook instead of `useService()`:
558
-
559
- ```diff
560
- -import { useService } from '@xstate/react';
561
- +import { useActor } from '@xstate/react';
562
-
563
- -const [state, send] = useService(someActor);
564
- +const [state, send] = useActor(someActor);
565
- ```
566
-
567
- ## Resources
568
-
569
- [State Machines in React](https://gedd.ski/post/state-machines-in-react/)
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ // this file might look strange and you might be wondering what it's for
3
+ // it's lets you import your source files by importing this entrypoint
4
+ // as you would import it if it was built with preconstruct build
5
+ // this file is slightly different to some others though
6
+ // it has a require hook which compiles your code with Babel
7
+ // this means that you don't have to set up @babel/register or anything like that
8
+ // but you can still require this module and it'll be compiled
9
+
10
+ // this bit of code imports the require hook and registers it
11
+ let unregister = require("../../../node_modules/@preconstruct/hook").___internalHook(typeof __dirname === 'undefined' ? undefined : __dirname, "../../..", "..");
12
+
13
+ // this re-exports the source file
14
+ module.exports = require("../src/index.ts");
15
+
16
+ unregister();
@@ -1,4 +1,4 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react"),require("xstate"),require("xstate/lib/behaviors")):"function"==typeof define&&define.amd?define(["exports","react","xstate","xstate/lib/behaviors"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).XStateReact={},t.React,t.XState,t.behaviors)}(this,(function(t,e,n,r){"use strict";
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("xstate"),require("xstate/lib/behaviors")):"function"==typeof define&&define.amd?define(["exports","react","xstate","xstate/lib/behaviors"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).XStateReact={},e.React,e.XState,e.behaviors)}(this,(function(e,t,n,r){"use strict";function u(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o,i=u(t),c=function(){return(c=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var u in t=arguments[n])Object.prototype.hasOwnProperty.call(t,u)&&(e[u]=t[u]);return e}).apply(this,arguments)};
2
2
  /*! *****************************************************************************
3
3
  Copyright (c) Microsoft Corporation.
4
4
 
@@ -12,4 +12,17 @@
12
12
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
13
13
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14
14
  PERFORMANCE OF THIS SOFTWARE.
15
- ***************************************************************************** */var u,i=function(){return(i=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var u in e=arguments[n])Object.prototype.hasOwnProperty.call(e,u)&&(t[u]=e[u]);return t}).apply(this,arguments)};function o(t,e){var n="function"==typeof Symbol&&t[Symbol.iterator];if(!n)return t;var r,u,i=n.call(t),o=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)o.push(r.value)}catch(t){u={error:t}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(u)throw u.error}}return o}function c(t,e){for(var n=0,r=e.length,u=t.length;n<r;n++,u++)t[u]=e[n];return t}!function(t){t[t.Effect=1]="Effect",t[t.LayoutEffect=2]="LayoutEffect"}(u||(u={}));var a=e.useLayoutEffect;function f(t){var n=e.useRef();return n.current||(n.current={v:t()}),n.current.v}function s(t,e){var n,r,u=o([[],[]],2),i=u[0],c=u[1];try{for(var a=function(t){var e="function"==typeof Symbol&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}(t),f=a.next();!f.done;f=a.next()){var s=f.value;e(s)?i.push(s):c.push(s)}}catch(t){n={error:t}}finally{try{f&&!f.done&&(r=a.return)&&r.call(a)}finally{if(n)throw n.error}}return[i,c]}function l(t,e){(0,t.exec)(e.context,e._event.data,{action:t,state:e,_event:e._event})()}function v(t,r,v){void 0===r&&(r={});var p=f((function(){return"function"==typeof t?t():t})),d=r.context,h=r.guards,b=r.actions,y=r.activities,g=r.services,m=r.delays,x=r.state,O=function(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var u=0;for(r=Object.getOwnPropertySymbols(t);u<r.length;u++)e.indexOf(r[u])<0&&Object.prototype.propertyIsEnumerable.call(t,r[u])&&(n[r[u]]=t[r[u]])}return n}(r,["context","guards","actions","activities","services","delays","state"]),S=f((function(){var t={context:d,guards:h,actions:b,activities:y,services:g,delays:m},e=p.withConfig(t,(function(){return i(i({},p.context),d)}));return n.interpret(e,i({deferEvents:!0},O))}));return a((function(){var t;return v&&(t=S.subscribe(function(t,e,n){if("object"==typeof t)return t;var r=function(){};return{next:t,error:e||r,complete:n||r}}(v))),function(){null==t||t.unsubscribe()}}),[v]),a((function(){return S.start(x?n.State.create(x):void 0),function(){S.stop()}}),[]),a((function(){Object.assign(S.machine.options.actions,b),Object.assign(S.machine.options.guards,h),Object.assign(S.machine.options.activities,y),Object.assign(S.machine.options.services,g),Object.assign(S.machine.options.delays,m)}),[b,h,y,g,m]),function(t){var n=e.useRef([]),r=e.useRef([]);a((function(){var e=t.subscribe((function(t){var e,i;if(t.actions.length){var a=o(s(t.actions.filter((function(t){return"function"==typeof t.exec&&"__effect"in t.exec})),(function(t){return t.exec.__effect===u.Effect})),2),f=a[0],l=a[1];(e=n.current).push.apply(e,c([],o(f.map((function(e){return[e,t]}))))),(i=r.current).push.apply(i,c([],o(l.map((function(e){return[e,t]})))))}}));return function(){e.unsubscribe()}}),[]),a((function(){for(;r.current.length;){var t=o(r.current.shift(),2);l(t[0],t[1])}})),e.useEffect((function(){for(;n.current.length;){var t=o(n.current.shift(),2);l(t[0],t[1])}}))}(S),S}function p(t,e){var n=function(){for(var e=[],n=0;n<arguments.length;n++)e[n]=arguments[n];return function(){return t.apply(void 0,c([],o(e)))}};return Object.defineProperties(n,{name:{value:"effect:"+t.name},__effect:{value:e}}),n}function d(t){return"state"in t}function h(t){return"deferred"in t}var b=function(){};function y(t){return"getSnapshot"in t?t.getSnapshot():d(t)?t.state:void 0}function g(t,n){void 0===n&&(n=y);var r=e.useRef(t),u=e.useRef([]),i=o(e.useState((function(){return n(t)})),2),c=i[0],s=i[1],l=f((function(){return function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=t[0],i=r.current;h(i)&&i.deferred?u.current.push(n):i.send(n)}}));return a((function(){r.current=t,s(n(t));for(var e=t.subscribe({next:function(t){return s(t)},error:b,complete:b});u.current.length>0;){var i=u.current.shift();t.send(i)}return function(){e.unsubscribe()}}),[t]),[c,l]}var m=function(t,e){return t===e},x=function(t){return"state"in(n=t)&&"machine"in n?0!==("status"in(e=t)?e.status:e._status)?e.state:e.machine.initialState:d(t)?t.state:void 0;var e,n};t.asEffect=function(t){return p(t,u.Effect)},t.asLayoutEffect=function(t){return p(t,u.LayoutEffect)},t.useActor=g,t.useInterpret=v,t.useMachine=function(t,r){void 0===r&&(r={});var u=e.useCallback((function(t){var e=void 0===t.changed&&Object.keys(t.children).length;(t.changed||e)&&f(t)}),[]),i=v(t,r,u),c=o(e.useState((function(){var t=i.machine.initialState;return r.state?n.State.create(r.state):t})),2),a=c[0],f=c[1];return[a,i.send,i]},t.useSelector=function(t,n,r,u){void 0===r&&(r=m),void 0===u&&(u=x);var i=o(e.useState((function(){return n(u(t))})),2),c=i[0],a=i[1],f=e.useRef(c);return e.useEffect((function(){var e=function(t){r(f.current,t)||(a(t),f.current=t)},i=n(u(t));e(i);var o=t.subscribe((function(t){var r=n(t);e(r)}));return function(){return o.unsubscribe()}}),[n,r]),c},t.useService=function(t){return[o(g(t),1)[0],t.send]},t.useSpawn=function(t){return f((function(){return r.spawnBehavior(t)}))},Object.defineProperty(t,"__esModule",{value:!0})}));
15
+ ***************************************************************************** */function a(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var u=0;for(r=Object.getOwnPropertySymbols(e);u<r.length;u++)t.indexOf(r[u])<0&&Object.prototype.propertyIsEnumerable.call(e,r[u])&&(n[r[u]]=e[r[u]])}return n}function f(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,u,o=n.call(e),i=[];try{for(;(void 0===t||t-- >0)&&!(r=o.next()).done;)i.push(r.value)}catch(e){u={error:e}}finally{try{r&&!r.done&&(n=o.return)&&n.call(o)}finally{if(u)throw u.error}}return i}function s(e,t){for(var n=0,r=t.length,u=e.length;n<r;n++,u++)e[u]=t[n];return e}!function(e){e[e.Effect=1]="Effect",e[e.LayoutEffect=2]="LayoutEffect"}(o||(o={}));var l=t.useLayoutEffect;function v(e){var n=t.useRef();return n.current||(n.current={v:e()}),n.current.v}function b(e,t){var n,r,u=f([[],[]],2),o=u[0],i=u[1];try{for(var c=function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),a=c.next();!a.done;a=c.next()){var s=a.value;t(s)?o.push(s):i.push(s)}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=c.return)&&r.call(c)}finally{if(n)throw n.error}}return[o,i]}function p(e,t){(0,e.exec)(t.context,t._event.data,{action:e,state:t,_event:t._event})()}function d(e){var n=t.useRef([]),r=t.useRef([]);l((function(){var t=e.subscribe((function(e){var t,u;if(e.actions.length){var i=f(b(e.actions.filter((function(e){return"function"==typeof e.exec&&"__effect"in e.exec})),(function(e){return e.exec.__effect===o.Effect})),2),c=i[0],a=i[1];(t=n.current).push.apply(t,s([],f(c.map((function(t){return[t,e]}))))),(u=r.current).push.apply(u,s([],f(a.map((function(t){return[t,e]})))))}}));return function(){t.unsubscribe()}}),[]),l((function(){for(;r.current.length;){var e=f(r.current.shift(),2);p(e[0],e[1])}})),t.useEffect((function(){for(;n.current.length;){var e=f(n.current.shift(),2);p(e[0],e[1])}}))}function h(e,t,n){if("object"==typeof e)return e;var r=function(){};return{next:e,error:t||r,complete:n||r}}function y(e){for(var t=[],r=1;r<arguments.length;r++)t[r-1]=arguments[r];var u=f(t,2),o=u[0],i=void 0===o?{}:o,s=u[1],b=v((function(){return"function"==typeof e?e():e})),p=i.context,y=i.guards,g=i.actions,O=i.services,j=i.delays,m=i.state,x=a(i,["context","guards","actions","services","delays","state"]),S=i.activities,w=v((function(){var e={context:p,guards:y,actions:g,activities:S,services:O,delays:j},t=b.withConfig(e,(function(){return c(c({},b.context),p)}));return n.interpret(t,c({deferEvents:!0},x))}));return l((function(){var e;return s&&(e=w.subscribe(h(s))),function(){null==e||e.unsubscribe()}}),[s]),l((function(){return w.start(m?n.State.create(m):void 0),function(){w.stop()}}),[]),l((function(){Object.assign(w.machine.options.actions,g),Object.assign(w.machine.options.guards,y),Object.assign(w.machine.options.activities,S),Object.assign(w.machine.options.services,O),Object.assign(w.machine.options.delays,j)}),[g,y,S,O,j]),d(w),w}function g(e,t){var n=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return function(){return e.apply(void 0,s([],f(t)))}};return Object.defineProperties(n,{name:{value:"effect:"+e.name},__effect:{value:t}}),n}function O(e){return"state"in e}function j(e){return"deferred"in e}var m=function(){};function x(e){return"getSnapshot"in e?e.getSnapshot():O(e)?e.state:void 0}function S(e,n){void 0===n&&(n=x);var r=t.useRef(e),u=t.useRef([]),o=f(t.useState((function(){return n(e)})),2),i=o[0],c=o[1],a=v((function(){return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[0],o=r.current;j(o)&&o.deferred?u.current.push(n):o.send(n)}}));return l((function(){r.current=e,c(n(e));for(var t=e.subscribe({next:function(e){return c(e)},error:m,complete:m});u.current.length>0;){var o=u.current.shift();e.send(o)}return function(){t.unsubscribe()}}),[e]),[i,a]}function w(e){var t={exports:{}};return e(t,t.exports),t.exports
16
+ /*
17
+ object-assign
18
+ (c) Sindre Sorhus
19
+ @license MIT
20
+ */}var E=Object.getOwnPropertySymbols,_=Object.prototype.hasOwnProperty,C=Object.prototype.propertyIsEnumerable;function P(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}var V=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach((function(e){r[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var n,r,u=P(e),o=1;o<arguments.length;o++){for(var i in n=Object(arguments[o]))_.call(n,i)&&(u[i]=n[i]);if(E){r=E(n);for(var c=0;c<r.length;c++)C.call(n,r[c])&&(u[r[c]]=n[r[c]])}}return u},R={useSubscription:function(e){var t=e.getCurrentValue,n=e.subscribe,r=i.default.useState((function(){return{getCurrentValue:t,subscribe:n,value:t()}}));e=r[0];var u=r[1];return r=e.value,e.getCurrentValue===t&&e.subscribe===n||(r=t(),u({getCurrentValue:t,subscribe:n,value:r})),i.default.useDebugValue(r),i.default.useEffect((function(){function e(){if(!r){var e=t();u((function(r){return r.getCurrentValue!==t||r.subscribe!==n||r.value===e?r:V({},r,{value:e})}))}}var r=!1,o=n(e);return e(),function(){r=!0,o()}}),[t,n]),r}},k=(w((function(e,t){})),w((function(e){e.exports=R})));
21
+ /** @license React vundefined
22
+ * use-subscription.production.min.js
23
+ *
24
+ * Copyright (c) Facebook, Inc. and its affiliates.
25
+ *
26
+ * This source code is licensed under the MIT license found in the
27
+ * LICENSE file in the root directory of this source tree.
28
+ */var q=function(e,t){return e===t},L=function(e){return"state"in(n=e)&&"machine"in n?0!==("status"in(t=e)?t.status:t._status)?t.state:t.machine.initialState:O(e)?e.state:void 0;var t,n};e.asEffect=function(e){return g(e,o.Effect)},e.asLayoutEffect=function(e){return g(e,o.LayoutEffect)},e.useActor=S,e.useInterpret=y,e.useMachine=function(e){for(var r=[],u=1;u<arguments.length;u++)r[u-1]=arguments[u];var o=f(r,1),i=o[0],c=void 0===i?{}:i,a=t.useCallback((function(e){var t=void 0===e.changed&&Object.keys(e.children).length;(e.changed||t)&&b(e)}),[]),s=y(e,c,a),l=f(t.useState((function(){var e=s.machine.initialState;return c.state?n.State.create(c.state):e})),2),v=l[0],b=l[1];return[v,s.send,s]},e.useSelector=function(e,n,r,u){void 0===r&&(r=q),void 0===u&&(u=L);var o=t.useRef(n),i=t.useMemo((function(){var t,i=u(e),c=n(i);return{getSnapshot:function(){return i},getCurrentValue:function(){return c},setCurrentValue:function(e){c=e,null==t||t()},subscribe:function(n){t=n;var u=e.subscribe((function(e){i=e;var t=o.current(e);r(c,t)||(c=t,n())}));return function(){u.unsubscribe()}}}}),[e]),c=k.useSubscription(i);if(o.current!==n){var a=n(i.getSnapshot());r(c,a)||(c=a)}return l((function(){o.current=n,i.setCurrentValue(c)})),c},e.useService=function(e){return[f(S(e),1)[0],e.send]},e.useSpawn=function(e){return v((function(){return r.spawnBehavior(e)}))},Object.defineProperty(e,"__esModule",{value:!0})}));
package/es/types.d.ts CHANGED
@@ -1,39 +1,7 @@
1
1
  import { ActionMeta, ActionObject, EventObject, State, StateConfig } from 'xstate';
2
- export declare type Sender<TEvent extends EventObject> = (event: TEvent) => void;
3
- export interface Subscription {
4
- unsubscribe(): void;
5
- }
6
- export interface Observer<T> {
7
- next?: (value: T) => void;
8
- error?: (errorValue: any) => void;
9
- complete: () => void;
10
- }
11
- export interface Subscribable<T> {
12
- subscribe(observer: Observer<T>): Subscription;
13
- subscribe(next: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;
14
- }
15
2
  export declare type MaybeLazy<T> = T | (() => T);
16
- declare type ExcludeType<A> = {
17
- [K in Exclude<keyof A, 'type'>]: A[K];
18
- };
19
- declare type ExtractExtraParameters<A, T> = A extends {
20
- type: T;
21
- } ? ExcludeType<A> : never;
22
- declare type ExtractSimple<A> = A extends any ? {} extends ExcludeType<A> ? A : never : never;
23
- declare type NeverIfEmpty<T> = {} extends T ? never : T;
24
- export interface PayloadSender<TEvent extends EventObject> {
25
- /**
26
- * Send an event object or just the event type, if the event has no other payload
27
- */
28
- (event: TEvent | ExtractSimple<TEvent>['type']): void;
29
- /**
30
- * Send an event type and its payload
31
- */
32
- <K extends TEvent['type']>(eventType: K, payload: NeverIfEmpty<ExtractExtraParameters<TEvent, K>>): void;
33
- }
34
- export interface ActorRef<TEvent extends EventObject, TEmitted = any> extends Subscribable<TEmitted> {
35
- send: Sender<TEvent>;
36
- }
3
+ export declare type NoInfer<T> = [T][T extends any ? 0 : any];
4
+ export declare type Prop<T, K> = K extends keyof T ? T[K] : never;
37
5
  export declare enum ReactEffectType {
38
6
  Effect = 1,
39
7
  LayoutEffect = 2
@@ -60,5 +28,4 @@ export declare type ActionStateTuple<TContext, TEvent extends EventObject> = [
60
28
  ReactActionObject<TContext, TEvent>,
61
29
  State<TContext, TEvent>
62
30
  ];
63
- export {};
64
31
  //# sourceMappingURL=types.d.ts.map
package/es/useActor.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { Sender } from './types';
2
- import { ActorRef, EventObject } from 'xstate';
1
+ import { ActorRef, EventObject, Sender } from 'xstate';
3
2
  export declare function isActorWithState<T extends ActorRef<any>>(actorRef: T): actorRef is T & {
4
3
  state: any;
5
4
  };
@@ -1,8 +1,13 @@
1
- import { EventObject, StateMachine, State, Interpreter, InterpreterOptions, MachineOptions, Typestate, Observer } from 'xstate';
1
+ import { AreAllImplementationsAssumedToBeProvided, InternalMachineOptions, InterpreterFrom, InterpreterOptions, Observer, State, StateMachine } from 'xstate';
2
2
  import { MaybeLazy } from './types';
3
3
  import { UseMachineOptions } from './useMachine';
4
- export declare function useInterpret<TContext, TEvent extends EventObject, TTypestate extends Typestate<TContext> = {
5
- value: any;
6
- context: TContext;
7
- }>(getMachine: MaybeLazy<StateMachine<TContext, any, TEvent, TTypestate>>, options?: Partial<InterpreterOptions> & Partial<UseMachineOptions<TContext, TEvent>> & Partial<MachineOptions<TContext, TEvent>>, observerOrListener?: Observer<State<TContext, TEvent, any, TTypestate>> | ((value: State<TContext, TEvent, any, TTypestate>) => void)): Interpreter<TContext, any, TEvent, TTypestate>;
4
+ declare type RestParams<TMachine extends StateMachine<any, any, any, any, any, any>> = AreAllImplementationsAssumedToBeProvided<TMachine['__TResolvedTypesMeta']> extends false ? [
5
+ options: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta'], true>,
6
+ observerOrListener?: Observer<State<TMachine['__TContext'], TMachine['__TEvent'], any, TMachine['__TTypestate'], TMachine['__TResolvedTypesMeta']>> | ((value: State<TMachine['__TContext'], TMachine['__TEvent'], any, TMachine['__TTypestate'], TMachine['__TResolvedTypesMeta']>) => void)
7
+ ] : [
8
+ options?: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta']>,
9
+ observerOrListener?: Observer<State<TMachine['__TContext'], TMachine['__TEvent'], any, TMachine['__TTypestate'], TMachine['__TResolvedTypesMeta']>> | ((value: State<TMachine['__TContext'], TMachine['__TEvent'], any, TMachine['__TTypestate'], TMachine['__TResolvedTypesMeta']>) => void)
10
+ ];
11
+ export declare function useInterpret<TMachine extends StateMachine<any, any, any, any, any, any>>(getMachine: MaybeLazy<TMachine>, ...[options, observerOrListener]: RestParams<TMachine>): InterpreterFrom<TMachine>;
12
+ export {};
8
13
  //# sourceMappingURL=useInterpret.d.ts.map
@@ -54,20 +54,26 @@ function toObserver(nextHandler, errorHandler, completionHandler) {
54
54
  complete: completionHandler || noop
55
55
  };
56
56
  }
57
- export function useInterpret(getMachine, options, observerOrListener) {
58
- if (options === void 0) { options = {}; }
57
+ export function useInterpret(getMachine) {
58
+ var _a = [];
59
+ for (var _i = 1; _i < arguments.length; _i++) {
60
+ _a[_i - 1] = arguments[_i];
61
+ }
62
+ var _b = __read(_a, 2), _c = _b[0], options = _c === void 0 ? {} : _c, observerOrListener = _b[1];
59
63
  var machine = useConstant(function () {
60
64
  return typeof getMachine === 'function' ? getMachine() : getMachine;
61
65
  });
62
66
  if (process.env.NODE_ENV !== 'production' &&
63
67
  typeof getMachine !== 'function') {
64
- var _a = __read(useState(machine), 1), initialMachine = _a[0];
65
- if (machine !== initialMachine) {
68
+ var _d = __read(useState(machine), 1), initialMachine = _d[0];
69
+ if (getMachine !== initialMachine) {
66
70
  console.warn('Machine given to `useMachine` has changed between renders. This is not supported and might lead to unexpected results.\n' +
67
71
  'Please make sure that you pass the same Machine as argument each time.');
68
72
  }
69
73
  }
70
- var context = options.context, guards = options.guards, actions = options.actions, activities = options.activities, services = options.services, delays = options.delays, rehydratedState = options.state, interpreterOptions = __rest(options, ["context", "guards", "actions", "activities", "services", "delays", "state"]);
74
+ var context = options.context, guards = options.guards, actions = options.actions, services = options.services, delays = options.delays, rehydratedState = options.state, interpreterOptions = __rest(options, ["context", "guards", "actions", "services", "delays", "state"]);
75
+ // it's not defined in `TypegenMachineOptions` so we can't just unpack this property here freely
76
+ var activities = options.activities;
71
77
  var service = useConstant(function () {
72
78
  var machineConfig = {
73
79
  context: context,
@@ -1,5 +1,5 @@
1
- import { EventObject, StateMachine, State, Interpreter, InterpreterOptions, MachineOptions, StateConfig, Typestate, ActionFunction } from 'xstate';
2
- import { MaybeLazy, ReactActionFunction } from './types';
1
+ import { ActionFunction, AreAllImplementationsAssumedToBeProvided, EventObject, InternalMachineOptions, InterpreterFrom, InterpreterOptions, StateConfig, StateFrom, StateMachine } from 'xstate';
2
+ import { MaybeLazy, Prop, ReactActionFunction } from './types';
3
3
  export declare function asEffect<TContext, TEvent extends EventObject>(exec: ActionFunction<TContext, TEvent>): ReactActionFunction<TContext, TEvent>;
4
4
  export declare function asLayoutEffect<TContext, TEvent extends EventObject>(exec: ActionFunction<TContext, TEvent>): ReactActionFunction<TContext, TEvent>;
5
5
  export interface UseMachineOptions<TContext, TEvent extends EventObject> {
@@ -13,12 +13,12 @@ export interface UseMachineOptions<TContext, TEvent extends EventObject> {
13
13
  */
14
14
  state?: StateConfig<TContext, TEvent>;
15
15
  }
16
- export declare function useMachine<TContext, TEvent extends EventObject, TTypestate extends Typestate<TContext> = {
17
- value: any;
18
- context: TContext;
19
- }>(getMachine: MaybeLazy<StateMachine<TContext, any, TEvent, TTypestate>>, options?: Partial<InterpreterOptions> & Partial<UseMachineOptions<TContext, TEvent>> & Partial<MachineOptions<TContext, TEvent>>): [
20
- State<TContext, TEvent, any, TTypestate>,
21
- Interpreter<TContext, any, TEvent, TTypestate>['send'],
22
- Interpreter<TContext, any, TEvent, TTypestate>
16
+ declare type RestParams<TMachine extends StateMachine<any, any, any, any, any, any>> = AreAllImplementationsAssumedToBeProvided<TMachine['__TResolvedTypesMeta']> extends false ? [
17
+ options: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta'], true>
18
+ ] : [
19
+ options?: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta']>
23
20
  ];
21
+ declare type UseMachineReturn<TMachine extends StateMachine<any, any, any, any, any, any>, TInterpreter = InterpreterFrom<TMachine>> = [StateFrom<TMachine>, Prop<TInterpreter, 'send'>, TInterpreter];
22
+ export declare function useMachine<TMachine extends StateMachine<any, any, any, any, any, any>>(getMachine: MaybeLazy<TMachine>, ...[options]: RestParams<TMachine>): UseMachineReturn<TMachine>;
23
+ export {};
24
24
  //# sourceMappingURL=useMachine.d.ts.map
package/es/useMachine.js CHANGED
@@ -46,26 +46,29 @@ export function asEffect(exec) {
46
46
  export function asLayoutEffect(exec) {
47
47
  return createReactActionFunction(exec, ReactEffectType.LayoutEffect);
48
48
  }
49
- export function useMachine(getMachine, options) {
50
- if (options === void 0) { options = {}; }
49
+ export function useMachine(getMachine) {
50
+ var _a = [];
51
+ for (var _i = 1; _i < arguments.length; _i++) {
52
+ _a[_i - 1] = arguments[_i];
53
+ }
54
+ var _b = __read(_a, 1), _c = _b[0], options = _c === void 0 ? {} : _c;
51
55
  var listener = useCallback(function (nextState) {
52
56
  // Only change the current state if:
53
57
  // - the incoming state is the "live" initial state (since it might have new actors)
54
58
  // - OR the incoming state actually changed.
55
59
  //
56
60
  // The "live" initial state will have .changed === undefined.
57
- var initialStateChanged = nextState.changed === undefined &&
58
- Object.keys(nextState.children).length;
61
+ var initialStateChanged = nextState.changed === undefined && Object.keys(nextState.children).length;
59
62
  if (nextState.changed || initialStateChanged) {
60
63
  setState(nextState);
61
64
  }
62
65
  }, []);
63
66
  var service = useInterpret(getMachine, options, listener);
64
- var _a = __read(useState(function () {
67
+ var _d = __read(useState(function () {
65
68
  var initialState = service.machine.initialState;
66
69
  return (options.state
67
70
  ? State.create(options.state)
68
71
  : initialState);
69
- }), 2), state = _a[0], setState = _a[1];
72
+ }), 2), state = _d[0], setState = _d[1];
70
73
  return [state, service.send, service];
71
74
  }
package/es/useSelector.js CHANGED
@@ -1,20 +1,6 @@
1
- var __read = (this && this.__read) || function (o, n) {
2
- var m = typeof Symbol === "function" && o[Symbol.iterator];
3
- if (!m) return o;
4
- var i = m.call(o), r, ar = [], e;
5
- try {
6
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
7
- }
8
- catch (error) { e = { error: error }; }
9
- finally {
10
- try {
11
- if (r && !r.done && (m = i["return"])) m.call(i);
12
- }
13
- finally { if (e) throw e.error; }
14
- }
15
- return ar;
16
- };
17
- import { useEffect, useRef, useState } from 'react';
1
+ import { useMemo, useRef } from 'react';
2
+ import { useSubscription } from 'use-subscription';
3
+ import useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect';
18
4
  import { isActorWithState } from './useActor';
19
5
  import { getServiceSnapshot } from './useService';
20
6
  function isService(actor) {
@@ -31,22 +17,49 @@ var defaultGetSnapshot = function (a) {
31
17
  export function useSelector(actor, selector, compare, getSnapshot) {
32
18
  if (compare === void 0) { compare = defaultCompare; }
33
19
  if (getSnapshot === void 0) { getSnapshot = defaultGetSnapshot; }
34
- var _a = __read(useState(function () { return selector(getSnapshot(actor)); }), 2), selected = _a[0], setSelected = _a[1];
35
- var selectedRef = useRef(selected);
36
- useEffect(function () {
37
- var updateSelectedIfChanged = function (nextSelected) {
38
- if (!compare(selectedRef.current, nextSelected)) {
39
- setSelected(nextSelected);
40
- selectedRef.current = nextSelected;
20
+ var latestSelectorRef = useRef(selector);
21
+ var subscription = useMemo(function () {
22
+ var snapshot = getSnapshot(actor);
23
+ var current = selector(snapshot);
24
+ var notifySubscriber;
25
+ return {
26
+ getSnapshot: function () { return snapshot; },
27
+ getCurrentValue: function () { return current; },
28
+ setCurrentValue: function (newCurrent) {
29
+ current = newCurrent;
30
+ notifySubscriber === null || notifySubscriber === void 0 ? void 0 : notifySubscriber();
31
+ },
32
+ subscribe: function (callback) {
33
+ notifySubscriber = callback;
34
+ var sub = actor.subscribe(function (emitted) {
35
+ snapshot = emitted;
36
+ var next = latestSelectorRef.current(emitted);
37
+ if (!compare(current, next)) {
38
+ current = next;
39
+ callback();
40
+ }
41
+ });
42
+ return function () {
43
+ sub.unsubscribe();
44
+ };
41
45
  }
42
46
  };
43
- var initialSelected = selector(getSnapshot(actor));
44
- updateSelectedIfChanged(initialSelected);
45
- var sub = actor.subscribe(function (emitted) {
46
- var nextSelected = selector(emitted);
47
- updateSelectedIfChanged(nextSelected);
48
- });
49
- return function () { return sub.unsubscribe(); };
50
- }, [selector, compare]);
51
- return selected;
47
+ // intentionally omit `getSnapshot` and `compare`
48
+ // - `getSnapshot`: it is only supposed to read the "initial" snapshot of an actor
49
+ // - `compare`: is really supposed to be idempotent and the same throughout the lifetime of this hook (the same assumption is made in React Redux v7)
50
+ }, [actor]);
51
+ var currentSelected = useSubscription(subscription);
52
+ if (latestSelectorRef.current !== selector) {
53
+ var selected = selector(subscription.getSnapshot());
54
+ if (!compare(currentSelected, selected)) {
55
+ currentSelected = selected;
56
+ }
57
+ }
58
+ useIsomorphicLayoutEffect(function () {
59
+ latestSelectorRef.current = selector;
60
+ // required so we don't cause a rerender by setting state (this could create infinite rerendering loop with inline selectors)
61
+ // at the same time we need to update the value within the subscription so new emits can compare against what has been returned to the user as current value
62
+ subscription.setCurrentValue(currentSelected);
63
+ });
64
+ return currentSelected;
52
65
  }
@@ -1,5 +1,4 @@
1
- import { EventObject, State, Interpreter, Typestate } from 'xstate';
2
- import { PayloadSender } from './types';
1
+ import { EventObject, Interpreter, PayloadSender, State, TypegenConstraint, TypegenDisabled, Typestate } from 'xstate';
3
2
  export declare function getServiceSnapshot<TService extends Interpreter<any, any, any, any>>(service: TService): TService['state'];
4
3
  /**
5
4
  * @deprecated Use `useActor` instead.
@@ -10,5 +9,8 @@ export declare function getServiceSnapshot<TService extends Interpreter<any, any
10
9
  export declare function useService<TContext, TEvent extends EventObject, TTypestate extends Typestate<TContext> = {
11
10
  value: any;
12
11
  context: TContext;
13
- }>(service: Interpreter<TContext, any, TEvent, TTypestate>): [State<TContext, TEvent, any, TTypestate>, PayloadSender<TEvent>];
12
+ }, TTypesMeta extends TypegenConstraint = TypegenDisabled>(service: Interpreter<TContext, any, TEvent, TTypestate, TTypesMeta>): [
13
+ State<TContext, TEvent, any, TTypestate, TTypesMeta>,
14
+ PayloadSender<TEvent>
15
+ ];
14
16
  //# sourceMappingURL=useService.d.ts.map
package/lib/types.d.ts CHANGED
@@ -1,39 +1,7 @@
1
1
  import { ActionMeta, ActionObject, EventObject, State, StateConfig } from 'xstate';
2
- export declare type Sender<TEvent extends EventObject> = (event: TEvent) => void;
3
- export interface Subscription {
4
- unsubscribe(): void;
5
- }
6
- export interface Observer<T> {
7
- next?: (value: T) => void;
8
- error?: (errorValue: any) => void;
9
- complete: () => void;
10
- }
11
- export interface Subscribable<T> {
12
- subscribe(observer: Observer<T>): Subscription;
13
- subscribe(next: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;
14
- }
15
2
  export declare type MaybeLazy<T> = T | (() => T);
16
- declare type ExcludeType<A> = {
17
- [K in Exclude<keyof A, 'type'>]: A[K];
18
- };
19
- declare type ExtractExtraParameters<A, T> = A extends {
20
- type: T;
21
- } ? ExcludeType<A> : never;
22
- declare type ExtractSimple<A> = A extends any ? {} extends ExcludeType<A> ? A : never : never;
23
- declare type NeverIfEmpty<T> = {} extends T ? never : T;
24
- export interface PayloadSender<TEvent extends EventObject> {
25
- /**
26
- * Send an event object or just the event type, if the event has no other payload
27
- */
28
- (event: TEvent | ExtractSimple<TEvent>['type']): void;
29
- /**
30
- * Send an event type and its payload
31
- */
32
- <K extends TEvent['type']>(eventType: K, payload: NeverIfEmpty<ExtractExtraParameters<TEvent, K>>): void;
33
- }
34
- export interface ActorRef<TEvent extends EventObject, TEmitted = any> extends Subscribable<TEmitted> {
35
- send: Sender<TEvent>;
36
- }
3
+ export declare type NoInfer<T> = [T][T extends any ? 0 : any];
4
+ export declare type Prop<T, K> = K extends keyof T ? T[K] : never;
37
5
  export declare enum ReactEffectType {
38
6
  Effect = 1,
39
7
  LayoutEffect = 2
@@ -60,5 +28,4 @@ export declare type ActionStateTuple<TContext, TEvent extends EventObject> = [
60
28
  ReactActionObject<TContext, TEvent>,
61
29
  State<TContext, TEvent>
62
30
  ];
63
- export {};
64
31
  //# sourceMappingURL=types.d.ts.map
package/lib/useActor.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import { Sender } from './types';
2
- import { ActorRef, EventObject } from 'xstate';
1
+ import { ActorRef, EventObject, Sender } from 'xstate';
3
2
  export declare function isActorWithState<T extends ActorRef<any>>(actorRef: T): actorRef is T & {
4
3
  state: any;
5
4
  };
@@ -1,8 +1,13 @@
1
- import { EventObject, StateMachine, State, Interpreter, InterpreterOptions, MachineOptions, Typestate, Observer } from 'xstate';
1
+ import { AreAllImplementationsAssumedToBeProvided, InternalMachineOptions, InterpreterFrom, InterpreterOptions, Observer, State, StateMachine } from 'xstate';
2
2
  import { MaybeLazy } from './types';
3
3
  import { UseMachineOptions } from './useMachine';
4
- export declare function useInterpret<TContext, TEvent extends EventObject, TTypestate extends Typestate<TContext> = {
5
- value: any;
6
- context: TContext;
7
- }>(getMachine: MaybeLazy<StateMachine<TContext, any, TEvent, TTypestate>>, options?: Partial<InterpreterOptions> & Partial<UseMachineOptions<TContext, TEvent>> & Partial<MachineOptions<TContext, TEvent>>, observerOrListener?: Observer<State<TContext, TEvent, any, TTypestate>> | ((value: State<TContext, TEvent, any, TTypestate>) => void)): Interpreter<TContext, any, TEvent, TTypestate>;
4
+ declare type RestParams<TMachine extends StateMachine<any, any, any, any, any, any>> = AreAllImplementationsAssumedToBeProvided<TMachine['__TResolvedTypesMeta']> extends false ? [
5
+ options: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta'], true>,
6
+ observerOrListener?: Observer<State<TMachine['__TContext'], TMachine['__TEvent'], any, TMachine['__TTypestate'], TMachine['__TResolvedTypesMeta']>> | ((value: State<TMachine['__TContext'], TMachine['__TEvent'], any, TMachine['__TTypestate'], TMachine['__TResolvedTypesMeta']>) => void)
7
+ ] : [
8
+ options?: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta']>,
9
+ observerOrListener?: Observer<State<TMachine['__TContext'], TMachine['__TEvent'], any, TMachine['__TTypestate'], TMachine['__TResolvedTypesMeta']>> | ((value: State<TMachine['__TContext'], TMachine['__TEvent'], any, TMachine['__TTypestate'], TMachine['__TResolvedTypesMeta']>) => void)
10
+ ];
11
+ export declare function useInterpret<TMachine extends StateMachine<any, any, any, any, any, any>>(getMachine: MaybeLazy<TMachine>, ...[options, observerOrListener]: RestParams<TMachine>): InterpreterFrom<TMachine>;
12
+ export {};
8
13
  //# sourceMappingURL=useInterpret.d.ts.map
@@ -57,20 +57,26 @@ function toObserver(nextHandler, errorHandler, completionHandler) {
57
57
  complete: completionHandler || noop
58
58
  };
59
59
  }
60
- function useInterpret(getMachine, options, observerOrListener) {
61
- if (options === void 0) { options = {}; }
60
+ function useInterpret(getMachine) {
61
+ var _a = [];
62
+ for (var _i = 1; _i < arguments.length; _i++) {
63
+ _a[_i - 1] = arguments[_i];
64
+ }
65
+ var _b = __read(_a, 2), _c = _b[0], options = _c === void 0 ? {} : _c, observerOrListener = _b[1];
62
66
  var machine = useConstant_1.default(function () {
63
67
  return typeof getMachine === 'function' ? getMachine() : getMachine;
64
68
  });
65
69
  if (process.env.NODE_ENV !== 'production' &&
66
70
  typeof getMachine !== 'function') {
67
- var _a = __read(react_1.useState(machine), 1), initialMachine = _a[0];
68
- if (machine !== initialMachine) {
71
+ var _d = __read(react_1.useState(machine), 1), initialMachine = _d[0];
72
+ if (getMachine !== initialMachine) {
69
73
  console.warn('Machine given to `useMachine` has changed between renders. This is not supported and might lead to unexpected results.\n' +
70
74
  'Please make sure that you pass the same Machine as argument each time.');
71
75
  }
72
76
  }
73
- var context = options.context, guards = options.guards, actions = options.actions, activities = options.activities, services = options.services, delays = options.delays, rehydratedState = options.state, interpreterOptions = __rest(options, ["context", "guards", "actions", "activities", "services", "delays", "state"]);
77
+ var context = options.context, guards = options.guards, actions = options.actions, services = options.services, delays = options.delays, rehydratedState = options.state, interpreterOptions = __rest(options, ["context", "guards", "actions", "services", "delays", "state"]);
78
+ // it's not defined in `TypegenMachineOptions` so we can't just unpack this property here freely
79
+ var activities = options.activities;
74
80
  var service = useConstant_1.default(function () {
75
81
  var machineConfig = {
76
82
  context: context,
@@ -1,5 +1,5 @@
1
- import { EventObject, StateMachine, State, Interpreter, InterpreterOptions, MachineOptions, StateConfig, Typestate, ActionFunction } from 'xstate';
2
- import { MaybeLazy, ReactActionFunction } from './types';
1
+ import { ActionFunction, AreAllImplementationsAssumedToBeProvided, EventObject, InternalMachineOptions, InterpreterFrom, InterpreterOptions, StateConfig, StateFrom, StateMachine } from 'xstate';
2
+ import { MaybeLazy, Prop, ReactActionFunction } from './types';
3
3
  export declare function asEffect<TContext, TEvent extends EventObject>(exec: ActionFunction<TContext, TEvent>): ReactActionFunction<TContext, TEvent>;
4
4
  export declare function asLayoutEffect<TContext, TEvent extends EventObject>(exec: ActionFunction<TContext, TEvent>): ReactActionFunction<TContext, TEvent>;
5
5
  export interface UseMachineOptions<TContext, TEvent extends EventObject> {
@@ -13,12 +13,12 @@ export interface UseMachineOptions<TContext, TEvent extends EventObject> {
13
13
  */
14
14
  state?: StateConfig<TContext, TEvent>;
15
15
  }
16
- export declare function useMachine<TContext, TEvent extends EventObject, TTypestate extends Typestate<TContext> = {
17
- value: any;
18
- context: TContext;
19
- }>(getMachine: MaybeLazy<StateMachine<TContext, any, TEvent, TTypestate>>, options?: Partial<InterpreterOptions> & Partial<UseMachineOptions<TContext, TEvent>> & Partial<MachineOptions<TContext, TEvent>>): [
20
- State<TContext, TEvent, any, TTypestate>,
21
- Interpreter<TContext, any, TEvent, TTypestate>['send'],
22
- Interpreter<TContext, any, TEvent, TTypestate>
16
+ declare type RestParams<TMachine extends StateMachine<any, any, any, any, any, any>> = AreAllImplementationsAssumedToBeProvided<TMachine['__TResolvedTypesMeta']> extends false ? [
17
+ options: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta'], true>
18
+ ] : [
19
+ options?: InterpreterOptions & UseMachineOptions<TMachine['__TContext'], TMachine['__TEvent']> & InternalMachineOptions<TMachine['__TContext'], TMachine['__TEvent'], TMachine['__TResolvedTypesMeta']>
23
20
  ];
21
+ declare type UseMachineReturn<TMachine extends StateMachine<any, any, any, any, any, any>, TInterpreter = InterpreterFrom<TMachine>> = [StateFrom<TMachine>, Prop<TInterpreter, 'send'>, TInterpreter];
22
+ export declare function useMachine<TMachine extends StateMachine<any, any, any, any, any, any>>(getMachine: MaybeLazy<TMachine>, ...[options]: RestParams<TMachine>): UseMachineReturn<TMachine>;
23
+ export {};
24
24
  //# sourceMappingURL=useMachine.d.ts.map
package/lib/useMachine.js CHANGED
@@ -51,27 +51,30 @@ function asLayoutEffect(exec) {
51
51
  return createReactActionFunction(exec, types_1.ReactEffectType.LayoutEffect);
52
52
  }
53
53
  exports.asLayoutEffect = asLayoutEffect;
54
- function useMachine(getMachine, options) {
55
- if (options === void 0) { options = {}; }
54
+ function useMachine(getMachine) {
55
+ var _a = [];
56
+ for (var _i = 1; _i < arguments.length; _i++) {
57
+ _a[_i - 1] = arguments[_i];
58
+ }
59
+ var _b = __read(_a, 1), _c = _b[0], options = _c === void 0 ? {} : _c;
56
60
  var listener = react_1.useCallback(function (nextState) {
57
61
  // Only change the current state if:
58
62
  // - the incoming state is the "live" initial state (since it might have new actors)
59
63
  // - OR the incoming state actually changed.
60
64
  //
61
65
  // The "live" initial state will have .changed === undefined.
62
- var initialStateChanged = nextState.changed === undefined &&
63
- Object.keys(nextState.children).length;
66
+ var initialStateChanged = nextState.changed === undefined && Object.keys(nextState.children).length;
64
67
  if (nextState.changed || initialStateChanged) {
65
68
  setState(nextState);
66
69
  }
67
70
  }, []);
68
71
  var service = useInterpret_1.useInterpret(getMachine, options, listener);
69
- var _a = __read(react_1.useState(function () {
72
+ var _d = __read(react_1.useState(function () {
70
73
  var initialState = service.machine.initialState;
71
74
  return (options.state
72
75
  ? xstate_1.State.create(options.state)
73
76
  : initialState);
74
- }), 2), state = _a[0], setState = _a[1];
77
+ }), 2), state = _d[0], setState = _d[1];
75
78
  return [state, service.send, service];
76
79
  }
77
80
  exports.useMachine = useMachine;
@@ -1,23 +1,9 @@
1
1
  "use strict";
2
- var __read = (this && this.__read) || function (o, n) {
3
- var m = typeof Symbol === "function" && o[Symbol.iterator];
4
- if (!m) return o;
5
- var i = m.call(o), r, ar = [], e;
6
- try {
7
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
8
- }
9
- catch (error) { e = { error: error }; }
10
- finally {
11
- try {
12
- if (r && !r.done && (m = i["return"])) m.call(i);
13
- }
14
- finally { if (e) throw e.error; }
15
- }
16
- return ar;
17
- };
18
2
  Object.defineProperty(exports, "__esModule", { value: true });
19
3
  exports.useSelector = void 0;
20
4
  var react_1 = require("react");
5
+ var use_subscription_1 = require("use-subscription");
6
+ var use_isomorphic_layout_effect_1 = require("use-isomorphic-layout-effect");
21
7
  var useActor_1 = require("./useActor");
22
8
  var useService_1 = require("./useService");
23
9
  function isService(actor) {
@@ -34,23 +20,50 @@ var defaultGetSnapshot = function (a) {
34
20
  function useSelector(actor, selector, compare, getSnapshot) {
35
21
  if (compare === void 0) { compare = defaultCompare; }
36
22
  if (getSnapshot === void 0) { getSnapshot = defaultGetSnapshot; }
37
- var _a = __read(react_1.useState(function () { return selector(getSnapshot(actor)); }), 2), selected = _a[0], setSelected = _a[1];
38
- var selectedRef = react_1.useRef(selected);
39
- react_1.useEffect(function () {
40
- var updateSelectedIfChanged = function (nextSelected) {
41
- if (!compare(selectedRef.current, nextSelected)) {
42
- setSelected(nextSelected);
43
- selectedRef.current = nextSelected;
23
+ var latestSelectorRef = react_1.useRef(selector);
24
+ var subscription = react_1.useMemo(function () {
25
+ var snapshot = getSnapshot(actor);
26
+ var current = selector(snapshot);
27
+ var notifySubscriber;
28
+ return {
29
+ getSnapshot: function () { return snapshot; },
30
+ getCurrentValue: function () { return current; },
31
+ setCurrentValue: function (newCurrent) {
32
+ current = newCurrent;
33
+ notifySubscriber === null || notifySubscriber === void 0 ? void 0 : notifySubscriber();
34
+ },
35
+ subscribe: function (callback) {
36
+ notifySubscriber = callback;
37
+ var sub = actor.subscribe(function (emitted) {
38
+ snapshot = emitted;
39
+ var next = latestSelectorRef.current(emitted);
40
+ if (!compare(current, next)) {
41
+ current = next;
42
+ callback();
43
+ }
44
+ });
45
+ return function () {
46
+ sub.unsubscribe();
47
+ };
44
48
  }
45
49
  };
46
- var initialSelected = selector(getSnapshot(actor));
47
- updateSelectedIfChanged(initialSelected);
48
- var sub = actor.subscribe(function (emitted) {
49
- var nextSelected = selector(emitted);
50
- updateSelectedIfChanged(nextSelected);
51
- });
52
- return function () { return sub.unsubscribe(); };
53
- }, [selector, compare]);
54
- return selected;
50
+ // intentionally omit `getSnapshot` and `compare`
51
+ // - `getSnapshot`: it is only supposed to read the "initial" snapshot of an actor
52
+ // - `compare`: is really supposed to be idempotent and the same throughout the lifetime of this hook (the same assumption is made in React Redux v7)
53
+ }, [actor]);
54
+ var currentSelected = use_subscription_1.useSubscription(subscription);
55
+ if (latestSelectorRef.current !== selector) {
56
+ var selected = selector(subscription.getSnapshot());
57
+ if (!compare(currentSelected, selected)) {
58
+ currentSelected = selected;
59
+ }
60
+ }
61
+ use_isomorphic_layout_effect_1.default(function () {
62
+ latestSelectorRef.current = selector;
63
+ // required so we don't cause a rerender by setting state (this could create infinite rerendering loop with inline selectors)
64
+ // at the same time we need to update the value within the subscription so new emits can compare against what has been returned to the user as current value
65
+ subscription.setCurrentValue(currentSelected);
66
+ });
67
+ return currentSelected;
55
68
  }
56
69
  exports.useSelector = useSelector;
@@ -1,5 +1,4 @@
1
- import { EventObject, State, Interpreter, Typestate } from 'xstate';
2
- import { PayloadSender } from './types';
1
+ import { EventObject, Interpreter, PayloadSender, State, TypegenConstraint, TypegenDisabled, Typestate } from 'xstate';
3
2
  export declare function getServiceSnapshot<TService extends Interpreter<any, any, any, any>>(service: TService): TService['state'];
4
3
  /**
5
4
  * @deprecated Use `useActor` instead.
@@ -10,5 +9,8 @@ export declare function getServiceSnapshot<TService extends Interpreter<any, any
10
9
  export declare function useService<TContext, TEvent extends EventObject, TTypestate extends Typestate<TContext> = {
11
10
  value: any;
12
11
  context: TContext;
13
- }>(service: Interpreter<TContext, any, TEvent, TTypestate>): [State<TContext, TEvent, any, TTypestate>, PayloadSender<TEvent>];
12
+ }, TTypesMeta extends TypegenConstraint = TypegenDisabled>(service: Interpreter<TContext, any, TEvent, TTypestate, TTypesMeta>): [
13
+ State<TContext, TEvent, any, TTypestate, TTypesMeta>,
14
+ PayloadSender<TEvent>
15
+ ];
14
16
  //# sourceMappingURL=useService.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xstate/react",
3
- "version": "1.6.1",
3
+ "version": "2.0.0-pr2674-2021926101023",
4
4
  "description": "XState tools for React",
5
5
  "keywords": [
6
6
  "state",
@@ -18,6 +18,13 @@
18
18
  "main": "lib/index.js",
19
19
  "module": "es/index.js",
20
20
  "types": "lib/index.d.ts",
21
+ "typesVersions": {
22
+ "<4.0": {
23
+ "lib/index.d.ts": [
24
+ "index.v3.d.ts"
25
+ ]
26
+ }
27
+ },
21
28
  "sideEffects": false,
22
29
  "directories": {
23
30
  "lib": "lib",
@@ -47,7 +54,7 @@
47
54
  "peerDependencies": {
48
55
  "@xstate/fsm": "^1.0.0",
49
56
  "react": "^16.8.0 || ^17.0.0",
50
- "xstate": "^4.11.0"
57
+ "xstate": "^4.27.0-pr2674-2021926101023"
51
58
  },
52
59
  "peerDependenciesMeta": {
53
60
  "@xstate/fsm": {