How can I initialize xstate context with component props? #562
-
I am trying to figure out how I can update context based on component props. I think this example shows a way to initialize context value using another atom. If the atom was coming from another component or something, I think this is reasonable. However, if you just wanted to initialize context values with component props, is it possible? This obviously doesn't work, I know.interface Context {
name: string
value: string
}
const machine = createMachine<Context>({
initial: "idle",
context: {
name: "some name",
value: "",
},
states: {
idle: {},
},
})
const Component: React.FC<Props> = ({ value }) => {
machine.withContext({
...machine.context,
value
})
const machineAtom = atomWithMachine(machine)
const [state, send] = useAtom(machineAtom)
return (
<>
<p>{state.context.name}</p>
<p>{state.context.value}</p>
</>
)
} I am thinking there can be another way to pre-populate the context without using another atom when to initialize a machine atom... or not? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 8 replies
-
We just had some discussions recently in the closed PR #289. const Component = ({ props }) => {
const machineAtomRef = useRef()
if (!machineAtomRef) {
machineAtomRef.current = atomWithMachine(...)
}
...
} I think we should create a codesandbox example for this. |
Beta Was this translation helpful? Give feedback.
-
I just published a course related to this: https://twitter.com/dai_shi/status/1528897398839611392 Lesson 4 and 5 discuss about creating xstate machines from component props. |
Beta Was this translation helpful? Give feedback.
We just had some discussions recently in the closed PR #289.
So, if we need create a machine using component props, it means we need to create within the component lifecycle.
I think we should create a codesandbox example for this.
Since you raised this discussion, would you be willing to help?