Skip to content

Two way computed signals #722

@lucacasonato

Description

@lucacasonato

It'd be great if Preact supported two way computed signals. They are particularly useful when you "derive" a signal from a different signal. They are essentially a computed signal, with a setter function that would be called when the user assigns to the computed signal's value.

This is particularly useful when you have an object and you want to turn a property of that object into it's own signal that you can pass to a child component (while allowing that child component to modify the value).

An example:

export function Page() {
  const project = useSignal({ name: "abc" });
  const name = useComputed(
    () => project.value.name,
    (newName) => project.value = { ...project.value, newName },
  );

  return (
    <div>
      <h1>Project page</h1>
      <label>
        Project name:
        <Input bind:value={name} />
      </label>
    </div>
  );
}

export function Input(props: { "bind:value": Signal<string> }) {
  return <input value={props["bind:value"]} onInput={(e) => props["bind:value"] = e.currentTarget.value} />
}

The minimal API surface would be to accept a second callback in useComputed that acts as a setter function. A slightly nicer API would be to have useComputed take an object, with a get and set method on them (this would likely result in better code formatting with most formatters as compared to two unnamed callback functions.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions