#React context with state machine as global state

1 messages · Page 1 of 1 (latest)

plucky birch
#

When I create a context to manage my state globally with React,So when I invoke a child machine I can't access the machine ref from the parent machine ref as interpreted machine ref

​Instead, I got a weird object with an observable method in it, and when my child component re-renders then I got every thing works fine

dire lava
#

Thanks for asking here 🙂 Do you have a code sample to share?

plucky birch
#

Sure will share a sandbox shortly

plucky birch
plucky birch
#

@vivid swan

vivid swan
# plucky birch <@105633881952141312>

Can you please provide more detail on what doesn't work? E.g. what is expected and what is the actual result? I'm not sure what to do here - there are two buttons

#

Which should I click first, and what should I expect to see?

plucky birch
#

Hmmm ok, So the expected is when you click the "click to send test event to child machine" button to see an alert when the child machine invokes this action
{ actions: { testChildAction: () => { alert("test child event works now"); console.log("test child event works now"); }, }, },

@vivid swan

#

But instead this is not happening because the child machine is not interpreted somehow

#

but if you click the first button "Click to re-render the child" you will see the alert

vivid swan
#

The key is to useSelector which keeps it up to date:

const childRef = useSelector(parentRef, s => s.children.child);
plucky birch
#

Yeah, thanks it works now
but I wonder why I have to use useSelector!

vivid swan
#

Because state machine actors change state over time due to events

#

Selectors "observe" those state changes

#

Without observing, you may miss when the state actually changes