Skip to content

Signal.State.prototype.update to update values using callbacks #249

Open
@Ocean-OS

Description

@Ocean-OS

When using signals, often the value of a signal is not known, but a change needs to be made based on the current value. This pattern can be found in Svelte's stores, Solid's Signals, and React's useState, to name a few. This pattern leads to cleaner code with less clutter. Since using a callback in Signal.State.prototype.set is too ambiguous (setting the value to a function might be the preferred operation), it seems reasonable to add Signal.State.prototype.update. Here's some examples of how the update function would work:

let count = new Signal.State(0);
function increment() {
    count.update(c => c + 1);
}
function createCountdown(start, duration) {
    let countdown = new Signal.State(start);
    let interval = setInterval(()=>{
        countdown.update(c=> c - 1);
        if (countdown.get() === 0) clearInterval(interval);
    }, duration/start);
    return countdown;
}

function createTypewriter(text) {
    let typewriter = new Signal.State("");
    let chars = text.split('');

    function type(char) {
        return function() {
            typewriter.update(t => t + char);
        }
    };
    for (let index = 0; index < chars.length; index++) {
        setTimeout(type(chars[index]), 200 + index * 200);
    }
    return typewriter;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions