preactjs / signals

Manage state with style in every framework
https://preactjs.com/blog/introducing-signals/
MIT License
3.72k stars 91 forks source link

Extend the API with set method to match the Svelte store contract #299

Closed Thiagolino8 closed 11 months ago

Thiagolino8 commented 1 year ago

First of all, thank you for the library!

The .subscribe() method has already been added to the library, and it was a great addition as it makes it compatible with the svelte $ syntax using the store contract, but only the getter part of the contract was added, but it would be great also take advantage of the setter's part of the contract. With a .set() method that behaves exactly like the setter value(), svelte can identify when a store is being assigned a new value with an = sign and uses the .set() method to assign this new value Before the .set() method: Code_phmWnfAz7b

After the .set() method: Code_cbARcr6viN

Thanks!

ryanatkn commented 1 year ago

I made a demo of two other cases where this is compelling for Svelte users. The first is two-way binding a signal to an input primitive, and the second is binding a signal containing an object to a select element, which is a slightly magical convenience in Svelte.

https://svelte.dev/repl/f5870de21ef146708e51a524af1dfc17?version=3.58.0

Although I'm a Svelte user and I'd like this feature, I can see having a second way to do the same thing in such a tight library is a significant downside.

andrewiggins commented 11 months ago

With Svelte 5 Runes coming, supporting & maintaining our version of Signals in Svelte is less appealing. However, has @developit mentioned in another comment, anyone can easily add support for our Signals as Svelte stores themselves with the following code:

import Signal from '@preact/signals-core';

Signal.prototype.set = function(value) {
  this.value = value;
};

Signal.prototype.update = function(callback) {
  this.value = callback(this.peek());
};