Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

const num = signal(3);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading