How to get the previous value for a solidjs signal?

Viewed 248

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())
})
1 Answers

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.

Related