简体   繁体   中英

socket.io in Svelte via store

I'd like to have socket.io available across the whole Svelte app. I don't know what I am doing wrong...

store.js

export const socket = writable();

This works

App.svelte

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

$socket = io();

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

This doesn't

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);
});

The code shown works as long as the execution order is guaranteed to be correct, ie the code in App running before the code in Component .

If it is not, you need to add additional logic to handle the store not being set. (You also probably should clean up these on event handlers via onDestroy as well.)

Eg you can use a reactive statement to check whether the store was set, if it is initialized with null :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM