user15023244
user15023244

Reputation:

How to swap two signals in SolidJS

How do you swap these signals so that b = prev a and a = prev b?

const [a, setA] = createSignal(50) 
const [b, setB] = createSignal(100)

function swapSignals() {}

Upvotes: 0

Views: 116

Answers (2)

snnsnn
snnsnn

Reputation: 13698

We extract values into local variables before running the state updates otherwise they will end up having the same value, and wrap the update logic into batch to prevent multiple re-renders:

import { batch, createSignal } from 'solid-js';
import { render } from 'solid-js/web';

const App = () => {
  const [a, setA] = createSignal(50)
  const [b, setB] = createSignal(100)

  const swapSignals = () => {
    const x = a();
    const y = b();
    batch(() => {
      setA(y);
      setB(x);
    });
  };

  return (
    <div>
      a: {a()} b: {b()}{` `}<button onClick={swapSignals}>Swap</button>
    </div>
  )
};

render(() => <App />, document.body);

https://playground.solidjs.com/anonymous/f744c2d3-8333-4f63-bf1e-d1e3665f81a2

Upvotes: 1

user15023244
user15023244

Reputation:

That was easy than I thought


setA(aPrev => {
  const bPrev = b()
  setB(aPrev)
  return bPrev
})

Upvotes: 1

Related Questions