solid-primitives icon indicating copy to clipboard operation
solid-primitives copied to clipboard

add createToggle

Open ghost opened this issue 2 years ago • 3 comments

Why this library has no toggle :)

function createToggle(initialValue) {
  const [value, setValue] = createSignal(initialValue)
  const toggle = setValue(value => !value)
  return [value, toggle]
}

ghost avatar Jan 11 '23 09:01 ghost

Maybe because it is a bit too trivial to deserve its own primitive? I'm not entirely sure.

atk avatar Jan 11 '23 09:01 atk

Maybe because it is a bit too trivial to deserve its own primitive? I'm not entirely sure.

Lazy as https://www.youtube.com/watch?v=nBTeLJUlOlg&ab_channel=watugotdotcom

ghost avatar Jan 11 '23 10:01 ghost

This may actually be worth adding as if you have a lot of "switches" you may end up writing that same toggle fn every single time.

const flip = (v: boolean): boolean => !v

function createToggle(initial_value: boolean, options?: SignalOptions<boolean>): [
  read: Accessor<boolean>,
  toggle: (new_value?: boolean) => boolean
] {
  const [value, setValue] = createSignal(initial_value, options)
  return [
    value,
    new_value => setValue(new_value === undefined ? flip : new_value)
  ]
}

https://playground.solidjs.com/anonymous/b1d84689-1ecc-432c-9838-df5c485eaa33

But probably not as a it's own package. I would like to merge these little signal helpers like createReducer or createTrigger into own separate space.

thetarnav avatar Aug 29 '23 17:08 thetarnav