Svelte meets socket.io with the power of store

Looking to implement socket.io globally in the Svelte application but encountering some issues...

store.js

export const socket = writable();

Success here

App.svelte

import { io } from "socket.io-client";
import { socket } from "./stores.js";

$socket = io();

$socket.on("orders", (orders) => {
    console.log(orders);
});

Not working here

App.svelte

import { io } from "socket.io-client";
import { socket } from "./stores.js";

$socket = io();

Component.svelte

import { socket } from "./stores.js";

$socket.on("orders", (orders) => {
    console.log(orders);
});

Answer №1

This particular code depends on the correct execution order, meaning that the code in App must run before the code in Component.

If this order is not guaranteed, you will have to implement additional logic to handle the scenario where the store is not yet set. It's also advisable to clean up any lingering on event handlers using onDestroy.

One approach could be implementing a reactive statement to verify if the store has been initialized with null:

$: if ($socket != null) {
    $socket.on("orders", (orders) => {
        console.log(orders);
    });
}

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

Oops! Looks like there's a type error in module "*.mdx" - it seems that it doesn't have the exported member "metadata". Maybe try using "import metadata from "*.mdx"" instead?

I am attempting to extract metadata from an mdx file. I have followed the guidelines outlined in NextJS Markdown Frontmatter, but encountered build errors. It is important to note that I am unable to utilize fs. Code Section Page.tsx File import Conte ...

What is the primary function for Express.js and Node.js 10 in Google Cloud Functions?

My Node JS version is 10 Express JS version: 4.16.1 I understand that for Node JS 8, the entry point should be "app" The generated code (from `npm install -g express-generator) www #!/usr/bin/env node /** * Module dependencies. */ var app = require( ...

Is it Possible to Insert Function from a For... in Loop?

Question: How is a function being attached to a variable's memory space without being explicitly assigned? Situation: I have developed a script to eliminate duplicate objects by comparing the values of object keys. However, after initializing the che ...

Touch events causing issues with scrolling due to knockout event binding

I encountered an issue with touchstart and touchmove events using knockout event binding where scrolling would get stuck (no preventDefault) and I also had trouble getting the click event to work properly. Interestingly, when I applied these events with ...

Exploring ways to transfer a function variable between files in React

Currently, I am working on a quiz application and have the final score stored in a function in app.js. My goal is to generate a bar graph visualization of the user's results (e.g. 6 right, 4 wrong) based on this score. To achieve this, I created anoth ...

Setting the font size for the entire body of a webpage globally is ineffective

Technology Stack: Nuxt.js + Vuetify.js Problem: Unable to set global body font size Solution Attempt: I tried to adjust the body font size to 40px in ~/assets/style/app.styl: // Import Vuetify styling ...

ReactJS has encountered an unhandled rejection, specifically a TypeError that states it cannot read the property 'push' of undefined. Users are facing difficulties when trying to push data to another

Having trouble with the app's functionality while trying to sign up and make a Stripe payment. The dashboard component doesn't seem to be loading. The error message I'm encountering: Unhandled Rejection (TypeError): Cannot read property &a ...

Incorporating a TextField in MUI Autocomplete for extended functionality

Within my React application, I have implemented a MUI Autocomplete field as a searchable dropdown. One of the options in this dropdown is a TextField, which should allow the user to input text. The TextField renders correctly, but unfortunately, clicking ...

The operation cannot be found

I am completely new to javascript, so here is my situation: I'm attempting to integrate a reading-position-indicator into my WordPress theme. To achieve this, I placed a div right behind the footer, close to all the script tags, as the position bar s ...

Changing focus to 'DIV' element without JQuery using Javascript and Angular's ng-click event

Instructions for using an Angular directive to set focus on a "DIV" element when clicked <a href="#" class="skipToContent" ng-click="showContent()" title="skip-to-main-content">Skip To Main Content</a> <div class="getFocus" role="button" ...

Guide to assigning a value to a model in AngularJS by utilizing a select input with an array of objects

I'm new to AngularJS and I've encountered a challenge that requires an elegant solution. My application receives a list from the server, which is used as the data source for the select tag's options. Let's assume this list represents a ...

Can you explain the distinction between the two methods of coding in jQuery?

1, $.each(a,f); 2,$("a").each(f); I understand the purpose of the last line, where it selects all <a> elements in the document and then calls the each() method to invoke function f for each selected element. However, I am unsure about the meani ...

notify a designated channel when ready for launch

I'm currently attempting to figure out how to send a message to a channel when the Discord bot is launched. I've experimented with this code: client.on('message', (message) => { client.on('ready', () => { channel = cli ...

Arrange the table according to the option selected in the dropdown menu

Attempting to organize my table according to the sorting choice selected by the user from a drop-down menu. I encountered this discussion and also that one, both relying on jQuery. However, none of them seem to be effective for me since I require a pure Ja ...

Playing videos directly within Facebook's Instant Articles on iPhones

Currently, I'm facing an issue with embedding a video in a Facebook Instant Article using an iframe. When attempting to play the video on an Android device, it plays within the article content instead of going full-screen. However, if I try to view ...

How to Use JavaScript to Fetch Data from a PHP Script

My current setup is working fine in terms of PHP, but I seem to be having trouble when it comes to the JavaScript aspect. It could be an issue with either: 1) My JavaScript code 2) The way my system is configured This is the PHP file that I am usin ...

Converting data from MySQL into an array of objects in PHP followed by JavaScript transformations

Below is the code I am using to transfer data from MySQL to a PHP array: while ( $row = $result->fetch_assoc() ) { $profile[] = array( "id" => $row[ "id" ], "first" => $row[ "first" ], "last" => $row[ "last" ], ...

The function _redux_redux_store__WEBPACK_IMPORTED_MODULE_2___default.a.getState is invalid

I've been searching everywhere but can't seem to find a solution for this bug. Can anyone lend some assistance? _redux_redux_store__WEBPACK_IMPORTED_MODULE_2___default.a.getState is throwing an error Here's my redux store setup: import {c ...

Clicking on the parent page prevents the hyperlink inside the iframe from working as expected

I am having an issue with a hyperlink inside an iframe. When I click on it in the parent page, it doesn't work. Here is how it is set up: iframe.html <h1>I'm inner page!</h1> <a id="shared" class="btn" href=&q ...

How can we consolidate the data gathered from mongodb - through aggregation, map reduce, or alternative methods?

I'm currently struggling with aggregation problems. I initially considered using map reduce or separate find queries combined with the async library to tackle the issue. Here is the schema for reference: db.keyword keyword: String start: Date sour ...