Skip to content
Advertisement

Trying to get a value from a custom store Svelte

i want to ask something, i have a custom store like

const BlaBla = (Data) => {
  const { subscribe, set, update } = writable(Data);
  return {
    subscribe,
    update,
    set,
    setData: (NewData) => {
      set(NewData)
    },
    getData: () => {
      return <<<<<<< "Here lies the problem, how i can get the "newData"?."
    }
  }
}

i will explaying the scenario, im creating a script for a fivem server and im using svelte, i create a store that get a Vehicle with some properties like Name, Last Name, Plate and bla bla, i create the setData(Vehicle) and pass a set(Vehicle) then in another method i want to “get” the plate only, one solution i did was creating a variable in the scope and instead of a set i did an update like this

const VehicleStore = (Vehicle) => {
  let Data = {} //Variable inside the scope
  const { subscribe, set, update } = writable(Vehicle);
  return {
    subscribe,
    update,
    set,
    setData: (NewData) => {
      update((s) => {
        s = NewData
        Data = s
        return s
      })
    },
    getData: () => {
      return Data.Plate
    }
  }
}

i don’t know if this is the actual solution, i think im missing something

Advertisement

Answer

Svelte exports a get function that can be used to resolve the value of a store once (it is syntactic sugar around subscribe).

So first you have to get the value of the store, then you can access its property:

import { get } from 'svelte/store';

// ...

  const store = writable(Data);
  const { subscribe, set, update } = store;

// ...

  return get(store).Plate

Note that accessing data like this will not be reactive because there is no persistent subscription to the store. You are generally not meant to use stores like that.

Instead you usually would use the store in a component’s markup using auto subscriptions via $:

$VehicleStore.Plate
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement