What could be causing my Svelte store's subscribe() method to trigger despite no change in value?

One of the Svelte stores I am using is called activeAccountIndexStore:

export const activeAccountIndexStore: Writable<number | "native" | null> =
  writable(null);

Initially, the value of the store is null, but it gets set to either a specific number or the string 'native' after some network activity.

There is also a subscribe() handler for this store, which is invoked by other Svelte components:

export const onChangeActiveAccount = (
  activeAccountHandler: ActiveAccountHandler
) => {
  activeAccountIndexStore.subscribe((newValue) => {
    log(`➡️➡️➡️➡️➡️ activeAccountIndexStore new value`, newValue);
    if (newValue !== null) {
      const activeAccount = getActiveAccount();
      activeAccountHandler(activeAccount);
    }
  });
};

An issue I'm experiencing is that the subscribe() change handler is being called repeatedly, even when the store value remains the same in consecutive changes:

stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value null
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value null
2stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0

The MDN documentation on Svelte stores explains:

A store is an object with a subscribe() method that allows interested parties to be notified whenever the store value changes.

However, in many cases above, the value of the store is not changing. I expected to see:

stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value null
stores.ts:68 ➡️➡️➡️➡️➡️ activeAccountIndexStore new value 0

Why is the subscribe() method of my Svelte store being triggered when the value hasn't changed?

Answer №1

The reason behind this issue lies in the need to reassess your Svelte components. When you subscribe to a store within a component and that component's instances are being created and removed, the subscribe event triggers because the value is considered new for that particular instance of the component.

This reassessment of the component can occur when it is unmounted and then remounted, or when the component receives new state.

An easy fix for this is to memoize the component state, such as placing the .subscribe() outside of the component.

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

Observing for form input in Nuxt.js

There is a form on my webpage, which includes the following elements: <div v-if="this.userdata.address == ''">Please enter your address</div> Your address <input type="text" v-model="userdata.address" ...

executing a hook within _app.tsx in Next.js

The issue I'm facing involves the rendering of a hook that helps determine if my components are within the screen's view to trigger animations. This hook is executed in _app.tsx, however, it doesn't run when switching to another page. Oddly ...

Adjust the DOM based on the output of the function

I'm currently working on creating a list where only one element can be active at a time. The state is updating correctly, but I'm facing an issue with the isActive function. It only activates initially and doesn't trigger when the state chan ...

Establishing a global variable in Cypress through a function

My current workflow involves the following steps: 1) Extracting a field value from one page: var myID; cy.get('#MYID'). then(($txt) => { myID= $txt.text(); }) .should('not.equal', null); 2) Mo ...

Navigating the ropes of push-pull functionality in Bootstrap 5

How can I utilize push and pull in Bootstrap version 5.0.0-beta2? In Bootstrap 3, my code looks like this: <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" /> <div class="row"> <d ...

Difficulty with obtaining .responsetext in AJAX and PHP

On my real estate website, I have a form for users to 'Add a Property'. Although I will implement form validation later on, here is the current html/js code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR ...

Interfacing Electron Frontend with Python Backend through seamless communication

Upon completing the development of a Python CLI app, it became apparent that creating an Electron frontend for better user interaction was necessary. What is the best way for the Electron app to communicate with the Python app when a user action occurs on ...

Implementing visibility toggles for objects in three.js using a graphical user interface

I am interested in controlling the visibility of objects in my scene through a button on a GUI. The following function currently hides/shows objects individually: g3white.traverse(function(child){child.visible = true;}); g3black.traverse(function(child){ ...

Google Script: Implementing multiple conditions based on unique identifiers

A custom script has been designed to keep track of the frequency of VIN numbers repetitions and the status of parts arrival for each unique VIN Number (Car). For instance, if a VIN number appears 5 times, it indicates that five parts are expected to arriv ...

Saving the output of a function in Javascript/NodeJS to a variable

I've been attempting to save the output of a function into a variable, but it's not working as expected. I've exhausted all my ideas and possibilities. Perhaps I'm just making a silly mistake :D I'm working with NodeJS, using expre ...

Efficiently handling multiple JSON objects in a single PHP function

Currently, I am working on a project that involves populating two dropdown menus where the value of one depends on the other. Specifically, I have three dropdowns - one to select a class, and the other two for selecting subjects and exams based on the sele ...

The "useState" React Hook is restricted from being used in a class component. To utilize React Hooks, they can only be invoked within a React function component or a custom React Hook function

I am relatively new to React frontend development and I am currently working on adding a temporary drawer to my Material-UI NavBar. Here is the code snippet where I added the drawer: class Navbar extends Component { render() { const { authentic ...

Turning text into clickable links using JavaScript

I am faced with a scenario where I need to detect phone numbers within a string and convert them into clickable links. At the moment, using an external library is not an option. Here's the progress I've made so far: String: "This is my phone nu ...

Is it possible to uncheck a checkbox from a list, even if some of them are already unchecked?

I am attempting to implement a feature where checking a checkbox selects all others in the list, and unchecking one deselects all. Currently, only selecting one checkbox allows me to check all the rest, but unchecking one doesn't trigger the reverse a ...

Leveraging JSON data in a client-side JavaScript script

Recently, I started exploring node.js and express. One issue that I am currently facing is how to correctly retrieve json data in a client-side javascript file. I keep receiving a 404 error indicating that the .json file cannot be found. In my project&apo ...

Encasing newly inserted child components within my designated slot

If I have a component with a single slot and instead of simply rendering all its children, I want to wrap each element individually, the following approach can be taken: Vue.component('MyElement', { render: function(createElement){ for (l ...

Define unique positions for multiple shapes and then combine these shapes

import * as THREE from 'three'; import * as BufferGeometryUtils from 'three/addons/utils/BufferGeometryUtils.js'; const renderer = new THREE.WebGLRenderer(); renderer.setSize( window.innerWidth, window.innerHeight ); document.body.appe ...

Is it necessary to clean up the string to ensure it is safe for URLs and filenames?

I am looking for a way to generate a URL-safe filename in JavaScript that matches the one created using PHP. Here is the code snippet I currently have in PHP: <?php $clean_name = strtr($string, 'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÑÒÓÔÕ ...

What is the best method for removing node and then reinstalling it using nvm?

In my Mac, I have successfully installed Nodejs, but it was done using the usual method. However, in my new role, I've been asked to utilize NVM for Node installation. Can you guide me on the best approach to uninstall Node and then reinstall it with ...

Setting cookies with NextJS Route API post middleware

@ Using NextJS 13.3 with App Dir and API Routes. I am currently working on implementing an authentication system using NextJS with my external NodeJS backend. The process involves the frontend sending credentials to the backend, which validates them and r ...