JSFiddle - React, Tailwind, and code Playground
by Farzad YZ
JavaScript
const loginFormMachine = {
form: {
submit: "loading"
},
loading: {
resolve: "profile",
reject: "error"
},
profile: {
logout: "form"
},
error: {
tryAgain: "loading",
neverMind: "form"
}
}
const initialState = "form";
function transition(state, action) {
const newState = loginFormMachine[state][action];
if (newState) {
console.log(`Transitioning from ${state} to ${newState}`);
} else {
console.log(`Action ${action} on state ${state} is invalid and will be ignored`);
}
return newState;
}
function createStore(initialState) {
let state = initialState;
return {
getState() {
return state
},
dispatch(action) {
state = transition(state, action.type);
}
}
}
const appStore = createStore(initialState);
console.log(appStore.getState());
appStore.dispatch({
type: "submit"
});
console.log(appStore.getState());
setTimeout(() => {
appStore.dispatch({
type: "resolve"
});
appStore.dispatch({
type: "submit"
});
}, 2000);