aditya
aditya

Reputation: 1

Issue with @preact/signals-react useSignal not triggering re-render across components

I'm facing an issue with the @preact/signals-react library where a signal update in one component is not triggering a re-render in another component. Here's a simplified version of my code:

Store.tsx:

import { signal } from "@preact/signals-react";

interface DropedFileType {
  value?: {
    file_format?: string;
  };
}
export const DropedFile: DropedFileType = signal({});

ViewArea.tsx:

import React from "react";
import { useSignal } from "@preact/signals-react";
import { DropedFile } from "./Store";

function ViewArea() {
  const dropedFile = useSignal(DropedFile);

  return (
    <div>
      {dropedFile.value?.file_format === "3mf" && <h1>File format is 3mf</h1>}
    </div>
  );
}

export default ViewArea;

In this setup, when DropedFile.value is updated in another component, the change is not reflected in ViewArea until a manual re-render is triggered (e.g., by clicking somewhere on the page).

Has anyone faced a similar issue or have any suggestions on how to resolve this? Any help would be greatly appreciated!

I tried using the useSignal hook from @preact/signals-react to track changes in a signal defined in a separate store file (Store.tsx). I was expecting that when the signal's value is updated in one component, it would trigger a re-render in another component (ViewArea.tsx) where the signal is being used. However, the re-render is not happening automatically. Instead, the updated value is only reflected when I manually trigger a re-render, for example, by clicking somewhere on the page.

Upvotes: 0

Views: 1077

Answers (1)

rschristian
rschristian

Reputation: 2967

It looks like you haven't followed the setup instructions, found here. You must use the Babel plugin or the useSignals() hook, yet you're using neither.

// ViewArea.tsx
import React from "react";
import { useSignal } from "@preact/signals-react";
import { useSignals } from "@preact/signals-react/runtime";
import { DropedFile } from "./Store";

function ViewArea() {
  useSignals();
  const dropedFile = useSignal(DropedFile);

  return (
    <div>
      {dropedFile.value?.file_format === "3mf" && <h1>File format is 3mf</h1>}
    </div>
  );
}

export default ViewArea;

Upvotes: 1

Related Questions