Attempting to retrieve a value from a bespoke store in Svelte

Let me pose a question: I have created a custom store that looks like this:

const MyCustomStore = (Data) => {
  const { subscribe, set, update } = writable(Data);
  return {
    subscribe,
    update,
    set,
    setData: (NewData) => {
      set(NewData)
    },
    getData: () => {
      return <<<<<<< "Here lies the problem - how can I retrieve the 'newData'?"
    }
  }
}

Now, let me explain the scenario. I am developing a script for a FiveM server using Svelte. I have created a store that holds information about vehicles such as Name, Last Name, Plate, and more. I have a method called setData(Vehicle) which sets the data, but in another method, I only need to retrieve the plate. One solution I implemented was creating a variable within the scope and using update instead of set:

const VehicleStore = (Vehicle) => {
  let Data = {} // Variable within 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 am uncertain if this is the correct solution; it feels like something might be missing.

Answer №1

Svelte provides a convenient get function for retrieving the value of a store once (it essentially simplifies using subscribe).

First, you need to retrieve the value of the store before accessing its properties:

import { get } from 'svelte/store';

// ...

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

// ...

  return get(store).Plate

It's important to note that this method of accessing data is not reactive since there isn't an ongoing subscription to the store. This approach is generally discouraged.

Instead, it's recommended to use the store in a component's markup by utilizing auto subscriptions with $:

$VehicleStore.Plate

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Switch statement with reduced scope for factory

How can I narrow the type output of a factory create method using literal types? I've tried narrowing with if statements and discriminated unions, but since this is a creational method, I'm not sure if it's possible. class Radio { type: ...

What is the best way to implement media queries for mobile phones and desktop computers?

I've come across similar questions before but still can't wrap my head around it. Here's my dilemma: I want the index page of my website to display in desktop layout on desktops and mobile jquery on mobile devices. Currently, I have set up m ...

Sequelize: Query results do not have defined instance methods and properties

The Sequelize version is 6.6.2 Mysql2 version: 2.2.5 I have constructed my Model in the following manner and defined methods as shown: interface IUserAttributes { user_id: number; logon_name: string; user_password: string; full_name: string; di ...

What is the best method to transfer information between main.js and a specific directory?

Is there a way to efficiently pass data between the main and directory components? I would like to automatically activate the directive when main.js loads. Directive code: angular.module('dmv.shared.components'). directive('doImportPackag ...

Trigger a callback in KnockoutJS once all bindings have been successfully set up

I am facing a frustrating bug that is detailed here: <select> only shows first char of selected option and I am looking for a solution to remove the display:none from my select boxes in order to resolve this issue. Any ideas? Here's the binding ...

When utilizing express-handlebars to render, the error message "req.next() is not a valid function

Trying to display the login page of a web application. Developed using TypeScript, node.js, express, and express-handlebars The code being executed is as follows: import exphbs = require("express-handlebars"); import cookieParser = require(&quo ...

Tips for resolving a flickering issue that occurs when switching to an input field with our default value / placeholder plugin

In the realm of web development, numerous plugins cater to the implementation of HTML5's placeholder attribute in older browsers. The plugin we have opted for can be found here. Unlike some other alternatives, this particular plugin, with a few modif ...

What steps do I need to take in order to implement a recursive function that keeps track of the history of local variables

Check out this cool function that takes a multi-dimensional array and converts it into a single-dimensional array using recursion. It's pretty nifty because it doesn't use any global variables, so everything is contained within the function itsel ...

What could be the reason for this JSON being considered "invalid"?

Despite passing validation on jsonlint, both Firefox and Chrome are rejecting this JSON: { "messages": [ { "subject": "One" }, { "subject": "Two" }, { "subject": "Three" ...

The Angular 1.x Ajax request is not triggering the expected update in the view

I am encountering an issue with my Angular application where the data retrieved from a JSON file is not updating in the view when the JSON file is updated. It seems like the JSON file and the view are out of sync. As a newcomer to Angular, I am struggling ...

jQuery Plugin - iDisplayLength Feature

I am currently using DataTables version 1.10.10 and I am looking to customize the main plugin Javascript in order to change the iDisplayLength value to -1. This adjustment will result in displaying "All" by default on all data tables, allowing users to fil ...

Check out the CSS media query for screens with a maximum width on larger devices

Is there a way to preview a specific div and see how it appears on mobile devices? The HTML code for the div is obtained from an external source, like this: var external_html='<div>Responsive div</div>' + '<style>@media ...

What is the best way to execute a series of AJAX functions one after the other in JavaScript?

Currently, I am working on a project that involves editing multiple elements within a window simultaneously using AJAX. My goal is to have all "open for editing" elements saved when the user clicks the save button for the entire window. However, I encount ...

I am facing unexpected results while trying to search for a string array object using elemMatch in Mongoose

I am encountering an issue that I can't seem to resolve. I need to utilize a query search to match the data of one job with user data, but I'm facing some obstacles. The primary challenge is within my query search for the job where the data looks ...

Issue with Ajax communication to PHP script causing data not to be sent

I am developing a web application that functions as an extensive form which will later be converted into a PDF document. Upon submission of the form, all input data is sent to a PHP file where they are stored as variables to be included in the PDF. Some of ...

Convert millimeters to inches with a unique AngularJS filter that activates on click

I am currently working on a UI that requires users to enter dimensions for width and height. Within the UI, there are 2 buttons available - one for 'mm' and the other for 'inches'. When either of these buttons is pressed, the active cl ...

Update the value of a scope variable directly within a controller. Subsequently making a function call

Hey there, I just want to start by saying sorry in case this question has already been asked or if it seems silly. I'm pretty new to AngularJS and have managed to overcome CORS errors, set up login via Parse, and even created an API for my app using ...

Revamping JSON structure by identifying id references

I recently attempted to update the city name within the JSON object provided below. "City":[ { "Name":"Delhi", "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd", "Towns":[ ...

What is the best way to effectively utilize Material UI breakpoints in combination with styled components?

Here is my code: const FooterBox = styled(Box)` background: #4e738a; left: 0; right: 0; bottom: 0; width: 100%; color: #ffffff; ${p => p?.theme?.breakpoints.up('xs')} { margin: auto; display: flex; flex-direction ...

How can I use jQuery to hide each div of the same class individually when a user clicks on each div to close

I am working on a project where I have multiple notification boxes represented by divs with the same class. These boxes are set to fade in one after the other using jQuery. Each box also contains a 'close_box' div that acts as a button to close/h ...