preactpreact-signal

Can computed signals have variable like functions?


In one of my computed signal I need to read data on a file, which is a runtime function. As I need the computed signal to run on client I need to figure out how to input variables. I try this:

import { render } from "preact";
import { signal, computed } from "@preact/signals";

const text = signal('This is changed on client');

const textAndData = computed((num) => {
  const data = `And this data is read on the server: ${num}`
  return `${text.value}. ${data}`;
});

function Result() {
  const num = 3
  return (
    <>{textAndData(num).value}</>
  );
}

render(<Result />, document.getElementById("app"));

Playground

This yields error: TypeError: textAndData is not a function. Is there a way to achieve this? I can see that if I can create the signal inside the module (i.e. useSignal, useComputed) then I don't need to worry about this. But for the sake of signal management I want to declare all signals in a module and export them.


Solution

  • if you don't want to create a local state with useSignal and useComputed the best you can do is to create a new signal for num/data. This way you can have it in one place, and updating num from wherever you need will automatically trigger an update for textAndData.

    const num = signal(3);