Why doesn't @xstate/react useMachine rerender with change in subactor? #4633
Answered
by
davidkpiano
brandonchinn178
asked this question in
Q&A
-
I'm invoking an actor in a state, but sending events to the actor doesn't cause the overall component to rerender. What am I doing wrong? Minimal reprofunction App() {
const [state, _, actor] = useMachine(
createMachine({
initial: 'start',
states: {
start: {
invoke: {
src: createMachine({
context: { counter: 1 },
on: {
INC: {
actions: assign({
counter: ({ context }) => context.counter + 1,
})
}
}
}),
id: 'start',
},
},
},
})
)
return (
<>
<p>{state.children.start.getSnapshot().context.counter}</p>
<button onClick={() => state.children.start.send({ type: 'INC' })}>Increment</button>
</>
)
} Expected behaviorClicking button shows new counter Actual behaviorCounter is not updated |
Beta Was this translation helpful? Give feedback.
Answered by
davidkpiano
Dec 26, 2023
Replies: 1 comment 9 replies
-
Only the top-level actor gets subscribed in this situation. You should do this: const [state, _, actorRef] = useMachine(parentMachine);
const childRef = useSelector(actorRef, s => s.children.start);
const counter = useSelector(childRef, s => s.context.counter); |
Beta Was this translation helpful? Give feedback.
9 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Right now, you can use the inspect API to do this. In plain XState, it's this:
With React: