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

[v5] @xstate/react add options to createActorContext #4050

Merged
merged 17 commits into from
Jul 4, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
15 changes: 15 additions & 0 deletions .changeset/popular-guests-kneel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@xstate/react': major
---

The `options` prop has been added (back) to the `Context.Provider` component returned from `createActorContext`:

```tsx
const SomeContext = createActorContext(someMachine);

// ...

<SomeContext.Provider options={{ input: 42 }}>
{/* ... */}
</SomeContext.Provider>;
```
5 changes: 5 additions & 0 deletions .changeset/tame-lemons-rescue.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@xstate/react': minor
---

The `observerOrListener` argument has been removed from the 3rd argument of `createActorContext(logic, options)`.
47 changes: 24 additions & 23 deletions packages/xstate-react/src/createActorContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
AnyStateMachine,
SnapshotFrom,
InterpreterOptions,
Observer,
AreAllImplementationsAssumedToBeProvided,
MarkAllImplementationsAsProvided,
StateMachine,
Expand All @@ -32,49 +31,49 @@ type ToMachinesWithProvidedImplementations<TMachine extends AnyStateMachine> =
>
: never;

export function createActorContext<TMachine extends AnyActorLogic>(
actorLogic: TMachine,
interpreterOptions?: InterpreterOptions<TMachine>,
observerOrListener?:
| Observer<SnapshotFrom<TMachine>>
| ((value: SnapshotFrom<TMachine>) => void)
export function createActorContext<TLogic extends AnyActorLogic>(
actorLogic: TLogic,
interpreterOptions?: InterpreterOptions<TLogic>
): {
useSelector: <T>(
selector: (snapshot: SnapshotFrom<TMachine>) => T,
selector: (snapshot: SnapshotFrom<TLogic>) => T,
compare?: (a: T, b: T) => boolean
) => T;
useActorRef: () => ActorRefFrom<TMachine>;
useActorRef: () => ActorRefFrom<TLogic>;
Provider: (
props: {
children: React.ReactNode;
} & (TMachine extends AnyStateMachine
options?: InterpreterOptions<TLogic>;
} & (TLogic extends AnyStateMachine
? AreAllImplementationsAssumedToBeProvided<
TMachine['__TResolvedTypesMeta']
TLogic['__TResolvedTypesMeta']
> extends true
? {
logic?: TMachine;
logic?: TLogic;
}
: {
logic: ToMachinesWithProvidedImplementations<TMachine>;
logic: ToMachinesWithProvidedImplementations<TLogic>;
}
: { logic?: TMachine })
: { logic?: TLogic })
) => React.ReactElement<any, any>;
} {
const ReactContext = React.createContext<ActorRefFrom<TMachine> | null>(null);
const ReactContext = React.createContext<ActorRefFrom<TLogic> | null>(null);

const OriginalProvider = ReactContext.Provider;

function Provider({
children,
logic: providedLogic = actorLogic,
machine
machine,
options: providedOptions = interpreterOptions
}: {
children: React.ReactNode;
logic: TMachine;
logic: TLogic;
/**
* @deprecated Use `logic` instead.
*/
machine?: never;
options?: InterpreterOptions<TLogic>;
}) {
if (machine) {
throw new Error(
Expand All @@ -84,17 +83,19 @@ export function createActorContext<TMachine extends AnyActorLogic>(

const actor = (useActorRef as any)(
providedLogic,
interpreterOptions,
observerOrListener
) as ActorRefFrom<TMachine>;
providedOptions
) as ActorRefFrom<TLogic>;

return React.createElement(OriginalProvider, { value: actor, children });
return React.createElement(OriginalProvider, {
value: actor,
children
});
}

// TODO: add properties to actor ref to make more descriptive
Provider.displayName = `ActorProvider`;

function useContext(): ActorRefFrom<TMachine> {
function useContext(): ActorRefFrom<TLogic> {
const actor = React.useContext(ReactContext);

if (!actor) {
Expand All @@ -107,7 +108,7 @@ export function createActorContext<TMachine extends AnyActorLogic>(
}

function useSelector<T>(
selector: (snapshot: SnapshotFrom<TMachine>) => T,
selector: (snapshot: SnapshotFrom<TLogic>) => T,
compare?: (a: T, b: T) => boolean
): T {
const actor = useContext();
Expand Down
14 changes: 7 additions & 7 deletions packages/xstate-react/src/useActorRef.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,27 +84,27 @@ export function useActorRef<TLogic extends AnyActorLogic>(
machine: TLogic,
...[options = {}, observerOrListener]: RestParams<TLogic>
): ActorRefFrom<TLogic> {
const service = useIdleInterpreter(machine, options);
const actorRef = useIdleInterpreter(machine, options);

useEffect(() => {
if (!observerOrListener) {
return;
}
let sub = service.subscribe(toObserver(observerOrListener));
let sub = actorRef.subscribe(toObserver(observerOrListener));
return () => {
sub.unsubscribe();
};
}, [observerOrListener]);

useEffect(() => {
service.start();
actorRef.start();

return () => {
service.stop();
service.status = InterpreterStatus.NotStarted;
(service as any)._initState();
actorRef.stop();
actorRef.status = InterpreterStatus.NotStarted;
(actorRef as any)._initState();
};
}, []);

return service as any;
return actorRef as any;
}
147 changes: 146 additions & 1 deletion packages/xstate-react/test/createActorContext.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createMachine, assign, fromPromise } from 'xstate';
import { createMachine, assign, fromPromise, PersistedStateFrom } from 'xstate';
import { fireEvent, screen, render, waitFor } from '@testing-library/react';
import { useSelector, createActorContext, shallowEqual } from '../src';

Expand Down Expand Up @@ -326,4 +326,149 @@ describe('createActorContext', () => {
expect(screen.getByTestId('value').textContent).toBe('42');
});
});

it("should preserve machine's identity when swapping options using in-render `.provide`", () => {
const someMachine = createMachine({
context: { count: 0 },
on: {
inc: {
actions: assign({ count: ({ context }) => context.count + 1 })
}
}
});
const stubFn = jest.fn();
const SomeContext = createActorContext(someMachine);

const Component = () => {
const { send } = SomeContext.useActorRef();
const count = SomeContext.useSelector((state) => state.context.count);
return (
<>
<span data-testid="count">{count}</span>
<button data-testid="button" onClick={() => send({ type: 'inc' })}>
Inc
</button>
</>
);
};

const App = () => {
return (
<SomeContext.Provider
logic={someMachine.provide({
actions: {
testAction: stubFn
}
})}
>
<Component />
</SomeContext.Provider>
);
};

render(<App />);

expect(screen.getByTestId('count').textContent).toBe('0');
fireEvent.click(screen.getByTestId('button'));

expect(screen.getByTestId('count').textContent).toBe('1');

fireEvent.click(screen.getByTestId('button'));

expect(screen.getByTestId('count').textContent).toBe('2');
});

it('options can be passed to the provider', () => {
davidkpiano marked this conversation as resolved.
Show resolved Hide resolved
const machine = createMachine({
initial: 'a',
states: {
a: {
on: {
next: 'b'
}
},
b: {}
}
});
const SomeContext = createActorContext(machine);
let persistedState: PersistedStateFrom<typeof machine> | undefined =
undefined;

const Component = () => {
const actorRef = SomeContext.useActorRef();
const state = SomeContext.useSelector((state) => state);

persistedState = actorRef.getPersistedState?.();

return (
<div
data-testid="value"
onClick={() => {
actorRef.send({ type: 'next' });
}}
>
{state.value}
</div>
);
};

const App = () => {
return (
<SomeContext.Provider options={{ state: persistedState }}>
<Component />
</SomeContext.Provider>
);
};

const { unmount } = render(<App />);

expect(screen.getByTestId('value').textContent).toBe('a');

fireEvent.click(screen.getByTestId('value'));

// Ensure that the state machine without restored state functions as normal
expect(screen.getByTestId('value').textContent).toBe('b');

// unrender app
unmount();

// At this point, `state` should be `{ value: 'b' }`

// re-render app
render(<App />);

// Ensure that the state machine is restored to the persisted state
expect(screen.getByTestId('value').textContent).toBe('b');
});

it('input can be passed to the provider', () => {
const SomeContext = createActorContext(
createMachine({
types: {} as {
context: { doubled: number };
},
context: ({ input }) => ({
doubled: input * 2
})
})
);

const Component = () => {
const doubled = SomeContext.useSelector((state) => state.context.doubled);

return <div data-testid="value">{doubled}</div>;
};

const App = () => {
return (
<SomeContext.Provider options={{ input: 42 }}>
<Component />
</SomeContext.Provider>
);
};

render(<App />);

expect(screen.getByTestId('value').textContent).toBe('84');
});
});
12 changes: 0 additions & 12 deletions packages/xstate-react/test/typegenTypes.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -639,18 +639,6 @@ describe('createActorContext', () => {
{null}
</Context.Provider>
);
ret = (
<Context.Provider
// @ts-expect-error
options={{
actions: {
myAction: () => {}
}
}}
>
{null}
</Context.Provider>
);
ret = (
<Context.Provider
logic={machine.provide({
Expand Down