import joystick, { global_state } from "@joystick.js/ui-canary";
import Cart from '../../components/cart/index.js';
const Store = joystick.component({
events: {
'click [data-item-id]': (event = {}, instance = {}) => {
global_state.set((state = {}) => {
return {
...state,
cart: [
...state.cart || [],
{ id: event.target.getAttribute('data-item-id'), }
],
};
});
},
},
render: ({ data, component, i18n }) => {
return `
<div>
<div class="store">
<button data-item-id="book">Add a Book to Cart</button>
<button data-item-id="t-shirt">Add a T-Shirt to Cart</button>
<button data-item-id="apple">Add an Apple to Cart</button>
</div>
${component(Cart)}
</div>
`;
},
});
export default Store;
import joystick, { global_state } from '@joystick.js/ui-canary';
const Cart = joystick.component({
state: {
cart: [],
},
lifecycle: {
on_mount: (instance = {}) => {
global_state.on('change', (state = {}, event = '', user_event_label = '') => {
instance.set_state({ cart: state?.cart });
});
}
},
events: {
'click button': (event = {}, instance = {}) => {
global_state.set((state = {}) => {
return {
...state,
cart: [
...state.cart || [],
{ id: event.target.getAttribute('data-item-id'), }
],
};
});
},
},
render: ({ state, each, when }) => {
return `
<div>
<div class="items">
${when(state?.cart?.length === 0, `
<p>No items in cart</p>
`)}
${when(state?.cart?.length > 0, `
<ul>
${each(state?.cart, (item) => {
return `<li>${item.id} <button>X</button></li>`;
})}
</ul>
`)}
</div>
</div>
`;
},
});
export default Cart;