How initialize context for a machine created with createActorContext ? #4784
-
Hello there. I'm new to xstate and trying to implement it in a React app. I've used In v4, we could do something like this: const MyContext = createActorContext(myMachine);
function App() {
return (
<MyContext.Provider
machine={() =>
myMachine.withContext({ myValue: 'initialValue' })
}
>
<MyComponent />
</MyContext.Provider>
);
} But this is now deprecated. I've tried to match it with the new input api: const MyContext = createActorContext(myMachine, { input: { myValue: null } });
function App() {
return (
<MyContext.Provider
logic={() =>
createActor(myMachine, {
input: { myValue: 'initialValue' },
})
}
>
<MyComponent />
</MyContext.Provider>
);
} But that ended up with this error : So the only way I've found is to add a transitive state (loading) to update the context with an event, but that seems weird. 🤔 const myMachine = createMachine({
context: ({ input }) => ({
myValue: input.myValue,
}),
initial: "loading",
states: {
loading: {
on: {
LOADED: {
target: "step1",
actions: assign({
myValue: ({ event }) => event.myValue,
}),
},
},
},
step1: {
on: {
NEXT: "step2",
},
},
[...]
},
});
function MyComponent() {
useEffect(() => {
const myValue = localStorage.getItem('my.value');
actorRef.send({ type: "LOADED", myValue });
}, [myValue]);
[...]
} Is there any better way to do this ? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
It should look like this: const MyContext = createActorContext(myMachine);
function App() {
return (
<MyContext.Provider
logic={myMachine}
options={{
input: { myValue: 'initialValue' }
}}
>
<MyComponent />
</MyContext.Provider>
);
} Let me know if this works for you! I'll update the docs soon. |
Beta Was this translation helpful? Give feedback.
-
@davidkpiano does this still apply? I just gave it a shot and saw it isn't working: <MyMachineContext.Provider
logic={myMachine.provide({
actions: {
handleSetTab: assign(({ event }) => {
navigate({ search: { view: event.value } });
return { tab: event.value };
}),
},
})}
options={{input: { tab: view}}}
>
...
</MyMachineContext.Provider> |
Beta Was this translation helpful? Give feedback.
It should look like this:
Let me know if this works for you! I'll update the docs soon.