Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

How should I build my store for complex object with methods?

$
0
0

My object is like:

const inventory = {  maxSlots: 24,  content: [    {id: "item_01", quantity: 5, slotId: 0},    {id: "item_02", quantity: 2, slotId: 2},    {id: "item_03", quantity: 1, slotId: 6},  ]};

I need custom methods like:

  • inventory.getRemainingSlots()
  • inventory.getFirstFreeSlotid()
  • inventory.addItem() (this one depends on inventory.getFirstFreeSlotid())

How should I make this object reactive?

  • Single writable?
  • Custom store with get, set, update and subscribe methods?
  • Class instance with writable?
  • One writable for each single property, then a store of stores?

I've reached this point so far:

inventoryStore.js

function createStore() {    const { subscribe, set, update } = writable({        maxSlots: 8,        content: [            { id: "item_01", quantity: 5, slotId: 0 },            { id: "item_02", quantity: 2, slotId: 2 },            { id: "item_03", quantity: 1, slotId: 6 },        ],    });    return {        // Store methods        subscribe,        set,        update,        get: () => get({ subscribe }),        // Custom methods        getContent: () => {            // I can't use this in .svelte files             return inventoryStore.get().content;        },        getFirstFreeSlotId: () => {            const content = inventoryStore.get().content;            const maxSlots = inventoryStore.get().inventoryMaxSlots;            for (let _slotId = 0; _slotId < maxSlots; _slotId++) {                const foundItem = content.find(_x => _x.slotId === _slotId);                if (!foundItem?.id) {                    return _slotId;                }            }            return -1;        }    };}export const inventoryStore = createStore();

Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>