Creating Concurrent Svelte Applications with Local State Management

Note: Self-answer provided.

There are three primary methods in Svelte for passing data between components:

1. Utilizing Props

This involves passing data from a parent component to a child component.

  1. Data transfer is one-way only.
  2. Data can only be passed between immediate parent-child components.

2. Implementing and utilizing Context

Data can be passed from a parent to any nested child component.

  1. Data flow is unidirectional.
  2. Data cannot be passed outside the parent-child hierarchy.
  3. Context must be established when the parent component is initialized.

3. Using Svelte Store

This allows for setting, updating, and subscribing to data from any file or component.

  1. If multiple instances of the same app run, the store will retain only one value from either instance. storeVar.set() sets the value based on page load time. storeVar.update() uses the value from the last instance.

Purpose

The goal is to configure a Svelte app that detects multiple custom embed codes within the root index file and runs distinct instances of the app. Each embedded code includes additional data such as video size and aspect ratio. Consequently, the UI for each instance will adjust according to the attributes of the embedded code (passed as props to the App). Users may interact with the UI by clicking on different actions like screen sizes, which should trigger updates specific to that particular instance without affecting others.

Challenge

The current issues involve limitations in passing or updating values within components after initialization (issue 2.2, 2.3), or encountering difficulties where the store fails to retain values for every instance (3.1).

Answer №1

 

Solution (successfully tested)

To solve the issue, I constructed an array of objects containing the id and data. Instead of using set(), I utilized update(). Before adding new data to an instance in the array, I made sure to filter out any existing instances.

 

Code snippet (typescript)

package.json file:

"scripts": {
    "dev": "vite",
    ...
  },
  ...
  "dependencies": {
    "swiper": "^8.2.2"
  }

Index.html file:

  <body>
    <custom-element
      id="id_custom_element_987654321"
      videoid="987654321"
      size="7"
    ></custom-element>
    ...
</body>

Main.ts file:

const embedElements = document.querySelectorAll(
  "custom-element"
);
...
export default app;

Helpers.ts file:


// Svelte helpers
...

export const store.ts file:

type CommonCustomStoreFormatType<T> = Array<CustomStoreFormatType<T>>;
...

App.svelte file:

// passed props
  export let embedElementId: string;
  export let embedVideoid: string;
  setContext("contxt_videoid", embedVideoid);
...
</main>

Any other component (fetches store instance value):

  import { store_videoComments } from "./store";

  const videoId = getContext("contxt_videoId");
  ...

 

Output - logging $store_videoComments

[
    {
        "videoId": "987654321",
        "data": "[data1,data2,data3]"
    },
    {
        "videoId": "123456789",
        "data": "[data63,data74,data88]"
    }
]

 
The log displays that all app instance values are successfully stored. Feel free to share any issues you encounter with this method or suggest a better alternative in the comments section.

Note:

  • I aimed for minimal build size and hence refrained from including third-party packages to address the problem.
  • I did not utilize SvelteKit
  • Similar discussion can be found on this GitHub page

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

Struggling to import a React component for sharing purposes

I've developed a React component that I want to share through a locally hosted npm repository. To achieve this, I created the React component using typescript, transpiled it to JavaScript, and then published the resulting code to the repository. Howe ...

Send a variable from a next.js middleware to an API request

I've been attempting to pass a middleware variable to my API pages via "req" but have encountered some issues Even after trying to send the user token to pages using "req", it consistently returns null The middleware file in question is: pages/api/u ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

Performing a test on API GET Request with Playwright

I've been attempting to verify the GET status using this particular piece of code. Regrettably, I keep encountering an error message stating "apiRequestContext.get: connect ECONNREFUSED ::1:8080". If anyone has any insights or suggestions on how to re ...

How to update nested properties in Typescript using bracket notation

Imagine there is an interface and object with nested properties as shown below: interface Iobj { a: { a2:string }; b: string; } const obj: Iobj = { a:{ a2: "hello" } b: "world" }; Now let's say we have strings that ...

Strategies for effectively mocking an Angular service: During Karma Jasmine testing, ensure that the spy on service.getShipPhotos is expected to be called once. In the test, it should

Currently, I am working on testing a function called getSingleShip in Angular 12 using Karma-Jasmine 4. The aim is to verify if this function is being called by another function named retrieveShip. However, the test results indicate that getSingleShip has ...

Oops! Looks like an issue has popped up: using require() of an ES module is not supported when using recharts in combination with next.js

I've noticed some similar questions, but none of them seem to address my particular issue. I'm currently working on a webapp using next.js (with typescript). Within the app, I am utilizing recharts, however, I am encountering a compilation error: ...

Drizzle ORM retrieve unique string that is not a database column

I'm working with a SQL query that looks like this: SELECT * FROM ( SELECT 'car' AS type, model FROM car UNION SELECT 'truck' AS type, model FROM trucks ) vehicles; In Drizzle, I'm trying to replicate the 'car ...

Importing TypeScript enums into a Vue or browser context can lead to errors or the need for additional dependencies

I'm encountering a problem when trying to import type definitions from a separate module in my Vue project. Below is the structure of the typedefs I am attempting to import: import { Server, createServer } from "net"; export namespace Testable { ...

How can I use the Required utility type in TypeScript for nested properties?

I'm exploring how to utilize the Required keyword to ensure that all members are not optional in TypeScript. I've achieved success with it so far, but I've run into an issue where it doesn't seem to work for nested members of an interfa ...

Tips for successfully passing the dynamic state and setState to a function in typescript

I'm encountering an issue with passing dynamic state and setState into a function using Typescript. Despite trying to use Generics, I am facing complaints from Typescript. Here is the code snippet: const handleSelectTag = (tag: { color: string; labe ...

Step-by-step guide for importing a JSON file in React typescript using Template literal

I am facing an error while using a Template literal in React TypeScript to import a JSON file. export interface IData { BASE_PRICE: number; TIER: string; LIST_PRICE_MIN: number; LIST_PRICE_MAX: number; DISCOUNT_PART_NUM: Discout; } type Discoun ...

Utilizing the onscroll feature to trigger a function within a ScrollView

I am facing an issue with an animated view where I need to execute multiple events within the onScroll property. The current onScroll implementation is as follows: onScroll={ Animated.event( [{ nativeEvent: { conten ...

Error: An unexpected token < was caught in the TypeScript Express code

Using TypeScript to compile and run an Express server that simply serves an HTML file. However, encountering an error in the response under the network tab in Chrome for app.js: Uncaught SyntaxError: Unexpected token '<' Below is the server c ...

Learn how to utilize the "is" status in Postma within your code, even when this particular status is not included in the response

Service.ts Upon invoking this function, I receive a JSON response similar to the following: public signupuser(user: Users): Observable<boolean> { let headers = new Headers(); headers.append('Content-Type', 'application/json&a ...

Unable to access global functions in Typescript

My current setup involves using cloudflare workers with miniflare. I have structured a bindings.d.ts file as follows: export interface Bindings { ENV: string MYSQL_URL: string JWT_SECRET: string JWT_ACCESS_EXPIRATION_MINUTES: number JWT_REFRESH_E ...

Using TypeScript, let's take a closer look at an example of Angular

I am trying to replicate the chips example found at this link (https://material.angularjs.org/latest/#/demo/material.components.chips) using TypeScript. I have just started learning TypeScript this week and I am having some difficulties translating this co ...

Is there a way to automatically scroll to the bottom of a div when it first

Looking to enhance my application with a chat feature that automatically scrolls to the bottom of the chat page to display the latest messages. Utilizing VueJs: <template> <div id="app"> <div class="comments" ...

There was an issue thrown during the afterAll function: Unable to access properties of undefined

Recently, I upgraded my Angular project from version 15 to 15.1 and encountered an error while running tests. To replicate the issue, I created a new Angular 15.1 project using the CLI and generated a service with similar semantics to the one causing probl ...

Unable to resolve all parameters for the RouterUtilities class

My goal is to develop a RouterUtilities class that extends Angular's Router. Despite the app running and compiling smoothly, when I run ng build --prod, it throws an error message like this: ERROR in : Can't resolve all parameters for RouterUtil ...