Skip to content

Instantly share code, notes, and snippets.

@mwangaben
Last active August 7, 2021 15:11
Show Gist options
  • Save mwangaben/d09318ee72b17c636929a728e58aa578 to your computer and use it in GitHub Desktop.
Save mwangaben/d09318ee72b17c636929a728e58aa578 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// import {createMachine, assign} from 'xstate';
const createUser = function(context, event) {
// alert('Making User');
// console.log(context);
console.log(event.payload);
axios.post('/users', ).then(({data}) => data).catch(error => error);
}
const fetchUsers = () =>
fetch(`http://localhost:4000/users`).then((response) => response.json());
const registerMachine = Machine({
id: 'register',
initial: 'idle',
context: {
form: {
name: '',
email: '',
password: ''
},
users: [],
error: '',
retries: 0
},
states: {
idle: {
on: {
SUBMIT: 'submitting',
FETCH: 'loading'
},
},
loading: {
invoke: {
id: 'getUsers',
src: (context, event) => fetchUsers(context),
onDone: {
target: 'idle',
actions: assign({ users: (context, event) => event.data })
},
onError: {
target: 'failure',
actions: assign({ error: (context, event) => event.data })
}
}
},
submitting: {
// actions: ['registerUser'],
invoke: {
id: 'saveUser',
src: (context, event) => createUser(context, event),
onDone:{
target: 'success',
actions: assign({ users: (context, event) => context.users.push(event.data) })
},
onError: {
target: 'failure',
actions: assign({ error: (context, event) => event.data })
}
}
// on: {
// RESOLVE: 'success',
// REJECT: 'failure'
// }
},
success: {
on:{
SUCCESS:'inform'
}
},
inform:{
on: {
OK: 'idle'
}
},
failure: {
on: {
RETRY: {
target: 'idle',
actions: assign({
retries: (context, event) => context.retries + 1
})
}
}
},
actions: {
// registerUser
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment