Skip to content

Add $readable and $writable runes #9237

@vd-aloker

Description

@vd-aloker

Describe the problem

With stores, it's easy to pass a store to a function and have the function read or write its value:

function doSomething(theStore){
  const current = get(theStore);
  // ...
  theStore.set('New value')
}

let val = writable('')
doSomething(val)

With state runes, it's not as easy, because the underlying signal is not exposed. Now I'd have to pass in an object that wraps access to the state:

export function doSomethingWithState(state){
  const current = state.value;
  // ...
  state.value = 'New Value'
}

let val2 = $state('');

doSomethingWithState({ 
	get value() { return val2}, 
	set value(newValue) { val2 = newValue}
})

As far as I can see, there's no way to create a helper function or similar that could simplify this. As a result, I expect more boilerplate code when using state as a replacement for stores.

Describe the proposed solution

Given that it's not possible to create a helper function that creates the wrapper object, maybe it could prove useful to have $readable and $writable runes that cause the compiler to create those wrappers. $writable would add the setter, $readable would omit it.

let val2 = $state('');
const wrapped = $writable(val2)
doSomethingWithState(wrapped)

This gets compiled to

let val2 = $state('');
const wrapped = { 
  get value(){ return val2; }, 
  set value(newValue){ val2 = newValue }
};
doSomethingWithState(wrapped)

($readable would omit the setter)

Obviously, this is all pretty new to me, so maybe I'm missing something.

Alternatives considered

The alternative is creating the object with the getter/setter manually.

Importance

would make my life easier

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions