Skip to content

Instantly share code, notes, and snippets.

@devstojko
Last active March 10, 2020 21:29
Show Gist options
  • Save devstojko/7fe000cc2e438b2db97e9faf4e3beca6 to your computer and use it in GitHub Desktop.
Save devstojko/7fe000cc2e438b2db97e9faf4e3beca6 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 steps = {
one: {
valid: false,
completed: false,
searchData: []
},
two: {
valid: false,
completed: false
},
three: {
valid: false,
completed: false
}
}
const fetchUser = () =>
fetch(`https://api.myjson.com/bins/1dd62e`).then(response => response.json());
const stepMachine = Machine({
id: 'stepMachine',
initial: 'stepOne',
context: {
cart: {
passengers: 0,
vehicles: 0,
},
tripType: "SINGLE",
steps,
},
states: {
stepOne: {
initial: 'idle',
states: {
idle: {
on: {
SEARCH: {
target: 'loading'
}
},
},
loading: {
invoke: {
id: 'getRoutes',
src: (context, event) => fetchUser(),
onDone: {
target: 'idle',
actions: assign({
steps
})
},
onError: {
target: 'error',
actions: assign({ error: (context, event) => event.data })
}
}
},
error: {
},
},
on: {
NEXT: {
target: 'stepTwo',
actions: 'submitOne',
},
TO_STEP_2: {
target: 'stepTwo',
cond: 'isOneCompleted'
},
TO_STEP_3: {
target: 'stepThree',
cond: 'isTwoCompleted'
},
SET_TRIP_TYPE: {
actions: 'setTripType'
},
SET_VEHICLES: {
actions: 'setVehicles'
},
SET_PASSENGERS: {
actions: 'setPassengers'
}
}
},
stepTwo: {
on: {
NEXT: {
target: 'stepThree',
actions: 'submitTwo',
},
TO_STEP_1: {
target: 'stepOne',
cond: 'isOneCompleted'
},
TO_STEP_3: {
target: 'stepThree',
cond: 'isTwoCompleted'
}
}
},
stepThree: {
on: {
TO_STEP_2: {
target: 'stepTwo',
cond: 'isTwoCompleted'
},
TO_STEP_1: {
target: 'stepOne',
cond: 'isOneCompleted'
}
}
}
}
}, {
actions: {
submitOne: assign({
steps: ctx => ({
...ctx.steps,
one: {
completed: true
}
})
}),
submitTwo: assign({
steps: ctx => ({
...ctx.steps,
two: {
completed: true
}
})
}),
setTripType: assign({
tripType: (_, e) => e.payload
}),
setPassengers: assign({
cart: (ctx, e) => ({
...ctx.cart,
passengers: e.payload
})
}),
setVehicles: assign({
cart: (ctx, e) => ({
...ctx.cart,
vehicles: e.payload
})
}),
goBack: () => console.log('go back'),
submit: () => console.log('submit')
},
guards: {
isOneValid: ctx => ctx.steps.one.valid,
isOneCompleted: ctx => ctx.steps.one.completed,
isTwoCompleted: ctx => ctx.steps.two.completed,
isThreeCompleted: ctx => ctx.steps.three.completed
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment