Created
July 3, 2018 21:08
-
-
Save ilya-korotya/15ebdd4535e83ba1ea2a96954e2b18d3 to your computer and use it in GitHub Desktop.
Vanilla JS machine state
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
const result = document.querySelector('#result'); | |
const render = line => result.innerHTML = `${ result.innerHTML }<br />${ line }` | |
const service = { | |
getData() { | |
return Promise.resolve('{"answer":42}'); | |
} | |
} | |
const machine = { | |
dispatch(actionName, ...payload) { | |
const actions = this.transitions[this.state]; | |
const action = this.transitions[this.state][actionName]; | |
if (action) { | |
render(`action dispatched: ${ actionName }`); | |
action.apply(machine, payload); | |
} | |
}, | |
changeStateTo(newState) { | |
render(`state changed: ${ newState }`); | |
this.state = newState; | |
}, | |
state: 'idle', | |
transitions: { | |
'idle': { | |
click: function () { | |
this.changeStateTo('fetching'); | |
service.getData().then( | |
data => { | |
try { | |
this.dispatch('success', JSON.parse(data)); | |
} catch (error) { | |
this.dispatch('failure', error) | |
} | |
}, | |
error => this.dispatch('failure', error) | |
); | |
} | |
}, | |
'fetching': { | |
success: function (data) { | |
render(`<strong>And the answer is ${ data.answer }</strong>`); | |
this.changeStateTo('idle'); | |
}, | |
failure: function (error) { | |
this.changeStateTo('error'); | |
} | |
}, | |
'error': { | |
retry: function () { | |
this.changeStateTo('idle'); | |
this.dispatch('click'); | |
} | |
} | |
} | |
} | |
console.clear(); | |
render(`initial state: ${ machine.state }`); | |
machine.dispatch('click'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment