Last active
December 21, 2021 20:29
-
-
Save tzkmx/94d46065ebdab3481777cfe8ccfb6d13 to your computer and use it in GitHub Desktop.
Correct? reuse of model event creator in machine (xstate)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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