eguneys
eguneys

Reputation: 6406

How to get the previous value for a solidjs signal?

I want to get the previous value of a signal how?

const [route, setRoute] = createSignal(1)

createEffect(() => {
  console.log('route previous value is', route(0))
  console.log('route updated value is', route())
})

Upvotes: 4

Views: 1840

Answers (2)

Pierre
Pierre

Reputation: 13046

If you want the previous signal value to compute a new one, you can pass a function to the signal setter function that receives the previous value as the argument.

const [count, setCount] = createSignal(0)

// The setter also returns the updated value.
const newCount = setCount((prev) => prev + 1);

Source: createSignal API reference

Upvotes: 0

Nick
Nick

Reputation: 16586

The callback function you provide to createEffect can take an argument than is equal to the returned value from the effect function's last call. Therefore, you can do the following:

const [route, setRoute] = createSignal(1);

createEffect((prev) => {
  const updated = route();

  console.log('route previous value is', prev);
  console.log('route updated value is', updated);

  return updated;
}, route());

Note that the second argument you pass to createEffect is the initial value for prev.

This described in the createEffect section of the Solid API docs.

Upvotes: 2

Related Questions