#Is this good practice?
1 messages · Page 1 of 1 (latest)
From the looks of the diagram, it shows you really don't need the successful states per loaded data so you can model it using a single invocation that's a Promise.all
That's true ! But let's say I wanted to show on a UI which services had loaded so far ?
That needs separate modeling. Let me think
That can be done using an invoked callbacks instead of promises
Unfortunately that's not fully supported in the studio right now
But if you're interested in the XState config for it:
createMachine({
initial: 'idle',
states: {
idle: {on: {load: 'loading'}},
loading: {
on: {load_data_done: 'loaded'},
invoke: {
src: () => (sendBack) => {
loadSettings().then(settings => {
sendBack({type: 'data_loaded', key: 'settings', data: settings}).catch(err => {
sendBack({type: 'load_error', key: 'settings', error: err.toString()});
// Do the same for whatever you need loaded here
// when all the data is loaded
sendBack({type: 'load_data_done'})
})
})
}
}
},
loaded: {type: 'final'},
load_error: {type: 'final'}
}
})
Interesting problem though. It's similar to modeling streaming data in statecharts.
This makes sense to me. I'd assume the line: sendBack({type: 'load_data_done'}); would have to be sent conditional on checking whether ALL services had loaded ? (assuming they are loaded async / in parallel)
Yes
Got it ! Thanks again @crimson star 🙂
Glad to be helpful
@crimson star would you consider the invoked callbacks approach here better practice than the initial parallel loading states? My preference would go to the parallel states, but I'm not sure if there's deeper technical implications I'm missing there.
Really depends. If the promises are only used for data fetching and none are related to each other (no waterfall), nothing needs to happen in between (treat them as a single whole) and the timing is immediate (all data is fetched at once concurrently), then a callback is an overkill.
It's sort of a data fetching vs data streaming problem