Skip to content

Instantly share code, notes, and snippets.

@tzkmx
Last active December 21, 2021 20:29
Show Gist options
  • Select an option

  • Save tzkmx/94d46065ebdab3481777cfe8ccfb6d13 to your computer and use it in GitHub Desktop.

Select an option

Save tzkmx/94d46065ebdab3481777cfe8ccfb6d13 to your computer and use it in GitHub Desktop.
Correct? reuse of model event creator in machine (xstate)
// https://stately.ai/viz/8cf34aba-b602-4f85-93d2-cc4c2d1f4c06
import { createModel } from 'xstate/lib/model'
interface Fund {
label: string
$target: number
createdAt: Date
updatedAt: Date
}
type FundCreateInfo = Omit<Fund, 'createdAt' | 'updatedAt'>
interface Portfolio {
fund?: Fund
}
interface PortfolioActions {
events: {
createFund: (value: FundCreateInfo) => Fund
}
}
const portfolioModel = createModel<Portfolio, PortfolioActions>({
fund: undefined,
}, {
events: {
createFund: (fund: FundCreateInfo) => {
const date = new Date()
return {
createdAt: date,
updatedAt: date,
...fund
}
}
}
})
export const portfolioMachine = portfolioModel.createMachine({
context: portfolioModel.initialContext,
initial: 'empty',
states: {
empty: {
on: {
createFund: {
target: 'withBaseFund',
actions: portfolioModel.assign({
fund: (_, fundInfo) => portfolioModel.events.createFund(fundInfo)
})
}
}
},
withBaseFund: {
type: 'final'
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment