How to send callback with data?
I want pass "conn" with callback, to add in context with "assign".
How can I do this?
My code:
const connect = (context, event) => (callback, onEvent) => r.connect({host: 'localhost', port: 28015, db: 'config'}).then(conn => {
conn.on('close', () => {
callback('CONNECTION_LOST');
});
callback('CONNECTION_SUCCESS');
}).catch(err => callback('CONNECTION_ERROR'));
Machine({
initial: 'connect',
context: {},
states: {
connect: {
invoke: {
src: connect,
},
on: {
CONNECTION_SUCCESS: {
target: 'idle'
},
CONNECTION_ERROR: {
target: 'connect'
}
}
},
idle: {
on: {
CONNECTION_LOST: 'connect',
}
}
}
});
What is your use-case for doing this? There might be a better solution than handing over the parent component the entire conn object.
It's part of huge backend solution, we need control under separated connection's on different parts in system, if one of connection is closed, restart it and send event to all depended systems, and we want has vizualization of this processes. This product good to viz, bad on development, if it only for react and small systems then well, we mistakes in choice of this solution.
It's pretty simple to do this:
const connect = (context, event) => (callback) => r.connect({...}, (connection) => {
// ...
callback({ type: 'CONNECTION_SUCCESS', connection });
}).catch( ... )
Machine({
initial: 'connect',
context: {
connection: undefined
},
states: {
connect: {
invoke: {
src: connect,
},
on: {
CONNECTION_SUCCESS: {
target: 'idle',
actions: assign({ connection: (_, e) => e.connection })
},
CONNECTION_ERROR: {
target: 'connect'
}
}
},
// ...
}
});
The key is to explicitly do this in the CONNECTION_SUCCESS transition.
Expand your project documentation. This moment is not present.
@glebfeklistov Please be more courteous in your comments. Unless you are paying me to do this, you cannot tell me what to do.
If you would like to change that, I have an OpenCollective that you can donate to. Thanks!
Maybe then you can pay me for tips to improve the product?
to improve the product?
XState is not a product. It will always remain free.
Most helpful comment
@glebfeklistov Please be more courteous in your comments. Unless you are paying me to do this, you cannot tell me what to do.
If you would like to change that, I have an OpenCollective that you can donate to. Thanks!