简体   繁体   中英

Store in XSTATE for accessing across components?

I have component A and component B where in after some selection in Component A, Component B should be able to get update state or selection. I have allocated separated machines for MachineA and MachineB respectively. I want to know how to get the context of MachineB in Component B which gets updated in Component A.

For eg.: Component A fetches data from Machine A and updates context of Machine B with selected product. Now Component B should be able to access store of Machine B which is updated. Any idea how to do this? I do not want to pass state as props.

Lift the state up, and use context . Put both machines in the context, so all the components share the same instances of the machines.

You should provide some code, you are using reactjs and angular tags so is hard to know what you have con your code.

Anyways, I'm not sure if you are already invoking the B machine inside the A machine, thats the first step to connect them. The second step is using the B machine on component B but from the A machine. On react will be something like this

 // A machine file const AMachine = Machine({ id: "aState", initial: "initialState", invoke: [ { id: "bState", src: BMachine } ], states: {...}, } // A component const [state, send] = useMachine(AMachine); const AMachineContext = React.createContext(null); <AMachineContext.Provider value={state}> <BComponent /> </AMachineContext.Provider> // B component const aMachine = useContext(AMachineContext); const [bState] = useService(aMachine.children.bState);

I know that the question is a little bit old, but I built a little library on top of xstate that could solve the same problem without passing by context.

https://github.com/moh12594/xstate-store

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM