Enhance service returned by default interpreter with custom event creators #1755
-
|
Hi! When our app starts we want to invoke multiple services as singletons (auth, user, theme, etc) and then use and compose them in different ways during user session. There is one minor problem, as the services are global they will be used in many files in various ways and in a big team people can make mistakes. To avoid additional complexity I suggest to have a code like this // authService.js
import { createMachine, interpret } from '@xstate/fsm';
const authMachine = createMachine({
/* ... */
});
const authService = interpret(
authMachine,
{
logOut: () => ({ type: 'AUTH__LOG_OUT' }),
logIn: (email, password) => ({ type: 'AUTH__LOG_IN', data: { email, password } })
}
);
authService.start();
export default authService// Login screen
import authService from './services/authService'
/* ... */
<Button
label="Log in"
onClick={() => authService.logIn(email, password)}
/>This should be more reliable code then next one, imho // Login screen
import authService from './services/authService'
/* ... */
<Button
label="Log in"
onClick={() => authService.send({ type: 'AUTH__LOG_IN', data: { email, password })}
/>Note: I think it's a common practice for services in general. For example, https://reactnavigation.org/docs/navigation-actions/#setparams |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
|
This is similar to the ideas in Comlink; it's sort of a proxy for sending events. You can definitely do this in user-land, and perhaps XState can provide (opt-in) helper functions to help you do this: function createProxy(service) {
const handler = {
get(target, propKey, receiver) {
return (payload) => {
service.send(propKey, payload);
};
}
};
return new Proxy(service, handler);
}
const serviceProxy = createProxy(someService);
serviceProxy.TOGGLE()
// ... etc.Example: https://codesandbox.io/s/xstate-proxy-example-62w2i?file=/src/index.js There are a couple of issues with this approach, though:
|
Beta Was this translation helpful? Give feedback.
This is similar to the ideas in Comlink; it's sort of a proxy for sending events.
You can definitely do this in user-land, and perhaps XState can provide (opt-in) helper functions to help you do this:
Example: https://codesandbox.io/s/xstate-proxy-example-62w2i?file=/src/index.js
There are a couple of issues with this approach, though: