Skip to content

Instantly share code, notes, and snippets.

@DaveHudson
Last active May 22, 2020 10:40
Show Gist options
  • Save DaveHudson/777bcc58d199ed02cfc5be61b0719048 to your computer and use it in GitHub Desktop.
Save DaveHudson/777bcc58d199ed02cfc5be61b0719048 to your computer and use it in GitHub Desktop.
Generated by XState Viz: https://xstate.js.org/viz
const addItemToCart = (ctx, item) =>
new Promise ((resolve, reject) => {
const newItem = [{
id: ctx.items.length + 1,
name: item.name,
price: item.price,
quantity: item.quantity
}]
const items = [...ctx.items, ...newItem]
setTimeout(() => resolve(items), 1000)
})
const removeItemFromCart = (ctx, id) =>
new Promise((resolve, reject) => {
const index = ctx.items.findIndex(obj => obj.id === id)
console.log('index', index)
const items = [
...ctx.items.slice(0, index),
...ctx.items.slice(index + 1)
]
setTimeout(() => resolve(items), 1000)
})
const incrementItemInCart = (ctx, id, qty) =>
new Promise((resolve, reject) => {
// grab the object
const item = ctx.items.find(obj => obj.id === id)
console.log('item', item)
console.log('qty', qty)
const newQty = item.quantity + qty
console.log('newQty', newQty)
// increment the quantity by 2nd param
const newItem = {
...item,
quantity: newQty
}
console.log('new', newItem)
// return entire array
const index = ctx.items.findIndex(obj => obj.id === id)
console.log('index', index)
const items = [
...cxt.items.slice(0, index),
...ctx.items.slice(index + 1),
]
console.log('items', items)
})
const cartMachine = Machine({
id: 'cart',
initial: 'emptyCart',
context: {
items: [],
cartTotal: 0
},
states: {
emptyCart: {
on: {
ADDITEM: 'addToCart'
}
},
cart: {
on: {
ADDITEM: 'addToCart',
REMOVEITEM: 'removeFromCart',
INCREMENTITEM: 'incrementItem'
}
},
addToCart: {
invoke: {
src: 'addItemToCart',
onDone: {
target: 'cart',
actions: ['setContext']
},
onError: 'error'
}
},
removeFromCart: {
invoke: {
src: 'removeItemFromCart',
onDone: {
target: 'cart',
actions: ['setContext']
},
onError: 'error'
}
},
incrementItem: {
invoke: {
src: 'incrementItemInCart',
onDone: {
target: 'cart',
action: ['setContext']
},
onError: 'error'
}
},
decrementItem: {},
removeItem: {},
updateItemQuantity: {},
error: {}
}
}, {
services: {
addItemToCart: (ctx, e) => addItemToCart(ctx, {
id: 1,
name: 'My Prod',
price: 1220,
quantity: 1
}),
removeItemFromCart: (ctx, e) => removeItemFromCart(ctx, 2),
incrementItemInCart: (ctx, e) => incrementItemInCart(ctx, 1, 1)
},
actions: {
setContext: assign({
items: (ctx, e) => e.data
})
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment