2

Is it possible to have a Recoil-esque state management solution in Svelte?

I have an app where there is a "canvas" (just a div) that renders multiple elements. These elements (svgs or divs) are moveable/draggable/rotatable etc.

If I used a single svelte store for this, then the whole store would need to be updated every time any element is updated.

In React, the Recoil library solves this problem very elegantly. I'm wondering if it's possible to do something similar in Svelte.

Here is a basic attempt that seems to work. Please advise if I could improve in any way or if there are downsides to doing this.

import { writable, get } from "svelte/store";
let id = 0;
export const stateStore = writable({});
export const elementListStore = writable([]);

export function createElementStore(element) {
    stateStore.update(store => { 
        store[++id] = writable(element);
        return store;
    })
    return id;
}

export function getElementState(id) {
    const store = get(stateStore);
    console.log('store: ', store)
    return store[id];
}
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • 1
    Is it important to put everything in one big store instead of just returning a `writable` from your create function ? – Stephane Vanraes Sep 07 '22 at 05:00
  • Also, do you have to use a store in the first place? – H.B. Sep 07 '22 at 07:33
  • @StephaneVanraes How would I access that element later? That's a requirement. – faadhil hakkim Sep 09 '22 at 02:23
  • @H.B. Not sure I am following. What's the alternative? This is for a graphics editor project so we're talking about adding shapes, text etc and manipulating their dimensions and positions etc. Each change in position should trigger a re-render. I am not aware how this can be done without a store or some form of state management. – faadhil hakkim Sep 09 '22 at 02:25
  • All state in Svelte is reactive by default (regular variables). Stores are only necessary in specific cases like e.g. handling state in external scripts or passing it around globally rather than using component props. – H.B. Sep 09 '22 at 03:13

0 Answers0