SolidJSS
SolidJSโ€ข15mo agoโ€ข
15 replies
DH

Losing reactivity when importing a signal from a library that uses SolidJS

Hey ๐Ÿ‘‹
I have a library that uses SolidJS, and a few projects that import said library.
I have the following code in one of my library's util files:

import { createEffect, createSignal } from "solid-js";
import Vec2 from "./data/Vec2";

export const [windowSize, setWindowSize] = createSignal<Vec2>(
  Vec2.of(window.innerWidth, window.innerHeight),
);

createEffect(() => {
  console.log("lib", windowSize());
});

createEffect(() => {
  const onResize = () => setWindowSize(Vec2.of(window.innerWidth, window.innerHeight));
  window.addEventListener("resize", onResize);
  return () => window.removeEventListener("resize", onResize);
});

and the Vec2 class that I'm using (with all the other irrelevant methods removed, to keep the code snippet short):
export default class Vec2 {
  public x: number;
  public y: number;

  private constructor(x: number, y: number) {
    this.x = x;
    this.y = y;
  }

  public static of(x: number, y: number): Vec2 {
    return new Vec2(x, y);
  }
}


The code above works as expected inside the library; When the window is resized, the signal updates, and the console.log effect gets called.
The issue I have is inside another project, that imports my library. The effects there doesn't get called after the initial render.

Here's my index.tsx entrypoint in the example project, it's more-or-less the default one when setting up a new SolidJS project:
import { render } from "solid-js/web";
import App from "./App";

const root = document.getElementById("root");

if (import.meta.env.DEV && !(root instanceof HTMLElement)) {
  throw new Error(
    "Root element not found. Did you forget to add it to your index.html? Or maybe the id attribute got misspelled?",
  );
}

render(() => <App />, root!);


And the App.tsx:

import { type Component, createEffect } from "solid-js";
import { windowSize } from "nodeflow-lib";

const App: Component = () => {
  createEffect(() => {
    console.log("proj", windowSize());
  });

  return <h1>Test</h1>;
};

export default App;


Any hints on why the effect inside the example app only gets called once (on load), while the one inside the library works as intended?
image.png
Was this page helpful?