#Ignore signal instantiation in effect

12 messages · Page 1 of 1 (latest)

ebon cradle
#

I'm using an effect to perist changes to local storage. How can I prevent the signal's instantiation from triggering the effect which then pesists an empty payload to local storage?

  readonly items = signal<Item[]>([]);

  private save = effect(() =>
    Preferences.set({ key: 'items', value: JSON.stringify(this.items()) })
  );

Stackblitz

lean urchin
#

effect() needs to run at least once to register its dependencies (the signals invoked in its scope)

#

That being said you will to store seperatly a "first run" state somewhere

coarse wadi
#

My recommendation it's avoid usage of effect , in this case usage better toObservable and subcripbe in this observable to listening changes of signals

ebon cradle
#

I just converted all of my app from using observables to signals which simplified and minimized code complexity enourmously.

#

This is the last little gotcha.

coarse wadi
ebon cradle
coarse wadi
#

your refer a usage of variable boolean how flag how firstChangeToIgnore

#

if your implement this flag your effect should be breaking , why ? i don't know reason

coarse wadi
#

Doesn't it break after a few changes or a while? It happened to me in Angular 17.3 or 17.2 ? . I ended up using toObservable

ebon cradle
#

That example was a false positive. Back to the drawing board w/ an Observable.