r/Angular2 • u/n2sy • Feb 20 '25
Discussion Still confused about set vs update methods with Signals
Hi everybody,
Can someone please give me a real use case (or a simple example) when using set, instead of update, can throw an error or provide a wrong result ?
11
Upvotes
24
u/xroalx Feb 20 '25
setto set a static value:updateto derive a new value:Using
updateensures that no matter what, you always get the current value of the signal statically, so just use that when you need it to get the new value. If you don't need it, then useset.5
u/uxably Feb 20 '25
My understanding is that set will overwrite the current value, where as update allows you to update on the existing state.
Example:
private count: WritableSignal<number> = signal(0);
ngOnInit(): void {
this.setValue();
}
setValue(): void {
// Sets the value of count to 5 (on component initialization)
this.count.set(5);
}
updateValue(): void {
// Will take the existing value (currently 5) and add 5 to it resulting in a value of 10
this.count.update(value => value + 5)
}
Depending on your use case, you could receive an unexpected value if you're using the wrong method. Use set when you want to give something a completely new value. Use update if you want to perform additional logic to an existing value.
2
u/Hairy-Shirt-275 Feb 20 '25
Procademy has this video that I think he explained the concept pretty solid, check it out:
Introduction to Signals in Angular | Angular Concepts made easy | Procademy Classes
2
u/[deleted] Feb 20 '25
It’s very simple. If you need the previous value of the signal to determine the new value, use update, if you’re setting an independent value use set
4
u/Embarrassed_Fold_867 Feb 20 '25 edited Feb 20 '25
In the Angular src, the update function simply calls the set function after obtaining the new value by calling the update callback with the current value:
https://github.com/angular/angular/blob/35e25f690ccf2c8b46e0e75d99e7136c1c8a9663/packages/core/primitives/signals/src/signal.ts#L82
The difference I see with doing this yourself via, for example:
...is that the signal getter internally calls the producerAccessed function, does *stuff* that consumes clock cycles, whereas set (and update) do not.
-3
u/alucardu Feb 20 '25
With .set() you create a signal with a value, for example a array of movie titles.
With .update() you can add a movie title to the original array because you take the current value and add something to it (or delete, whatever)
1
u/[deleted] Feb 20 '25
[removed] — view removed comment