Skip to content

Instantly share code, notes, and snippets.

@DroopyTersen
Last active February 19, 2021 03:43
Show Gist options
  • Save DroopyTersen/9f27c912ca1797c55fa1592889444a83 to your computer and use it in GitHub Desktop.
Save DroopyTersen/9f27c912ca1797c55fa1592889444a83 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
// Available variables:
// - Machine
// - interpret
// - assign
// - send
// - sendParent
// - spawn
// - raise
// - actions
// - XState (all XState exports)
const baseUrl = "https://droopytersen-natandrewsayido.builtwithdark.com"
async function lookupGuest(streetNumber) {
let url = baseUrl + `/lookupGuest?lookupId=` + streetNumber;
let result = await fetch(url).then(resp => resp.json())
console.log(result);
return result.data.guests
}
async function submitRsvp(rsvp) {
let url = baseUrl + "/submitRsvp";
let result = await fetch(url, {
method: "POST",
body: JSON.stringify(rsvp),
headers: { "content-type": "application/json" }
}).then(resp => resp.json())
console.log(result);
return result.data.rsvp;
}
const checkCanSubmit = (context, event) => {
return true;
}
const checkHasResponded = (c) => c.guest && c.guest.rsvp;
const checkHasNotResponded = (c) => c.guest && !c.guest.rsvp;
const checkAlreadyChosen = (c) => c.guest
const rsvpMachine = Machine({
id: 'rsvp',
initial: 'unknown',
context: {
results: null,
guest: null
},
states: {
unknown: {
entry: assign({
results: () => null,
guest: () => null,
}),
on: {
FIND: "finding"
}
},
finding: {
invoke: {
id: "lookupGuest",
src: (context, event) => lookupGuest(event.lookupId || "5722"),
onDone: {
target: 'choosing',
actions: assign({
// store the results in context
results: (_, event) => event.data,
// if there was only one result, set the guest
guest: (_, event) => event.data.length === 1 ? event.data[0] : null
})
}
},
},
choosing: {
on: {
// Auto choose if only one choice
'': [{ target: "checkingRsvp", cond: checkAlreadyChosen }],
// Set the guest in context using passed index
CHOOSE: {
target: "checkingRsvp",
actions: assign({
guest: (context, event) => context.results[event.index]
})
},
}
},
// Transient State
// The guest has been selected, see if they've already responded.
checkingRsvp: {
on: {
'': [ {
target: "unresponded", cond: checkHasNotResponded
},{
target: "responded", cond: checkHasResponded
}],
}
},
unresponded: {
on: {
SUBMIT: "submitting"
}
},
submitting: {
invoke: {
id: "submitRsvp",
src: (context,event) => submitRsvp(event.rsvp),
onDone: {
target: "responded",
actions: assign({
guest: (context, event) => ({
...context.guest,
rsvp: event.data
})
})
}
}
},
responded: {
type: 'final'
},
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment