#Is there a more proper way to set value across components?

1 messages · Page 1 of 1 (latest)

novel pewter
#

I've tried an experiment of setting value across components.
The codes in the shot screen works, but it should be a better way to do this right?

modern coral
#

No, using the setter in multiple locations is the way to go. If you want, you can encapsulate the functionality in a context, but you can also keep it global.

novel pewter
#

Thank you

oak pollen
#

I would be extremely reluctant to hand out a raw setter like that.

The “owner ” of reactive state should constrain the possible ways in which that state can be modified. The definition of those mutators should be collocated with the state itself and exported (if absolutely necessary) instead of the setter.

// file: value.tsx
import { createSignal } from 'solid-js';

const [value, setValue] = createSignal(0);

const increment = (v: number) => v + 1;
const addThree = (v: number) => v + 3;
const update = {
  increment: () => setValue(increment),
  addThree: () => setValue(addThree),
};

export { update, value };

https://playground.solidjs.com/anonymous/e26301b5-e5dc-4d69-9304-10022a0b11e1

3. Read/Write segregation.

Solid is a purely reactive library. It was designed from the ground up with a reactive core. It's influenced by reactive principles developed by previous libraries.

oak pollen
#

Under most circumstances I would consider this a “code smell”:

import { value, update } from './value';

i.e. needing access to both the accessor and mutators at the same time.

Compare to:
https://playground.solidjs.com/anonymous/40c07288-1536-4f99-9f6f-283506f87667

// file: main.tsx
import { render } from 'solid-js/web';
import { value } from './value';
import { Increment } from './increment';
import { AddThree } from './add-three';

function App() {
  return (
    <>
      <p>{value()}</p>
      <Increment />
      <AddThree />
    </>
  );
}

render(() => <App />, document.getElementById('app')!);
// file: increment.tsx
import { update } from './value';

const { increment } = update;

function Increment() {
  return (
    <button type="button" onClick={increment}>
      +1
    </button>
  );
}

export { Increment };