Sub topic 10
Updating data locally with set and update
This chapter assumes you can create a resource with params and a loader, and that you know the status values from earlier chapters. It also assumes you know what reload() does. Here you will change a resource's value without calling the loader. You will see what that does to status(), and how to build an optimistic update that can roll back.
Why a resource is writable
A resource created with resource() or rxResource() is a WritableResource. Besides the read-only signals value, status, error, and isLoading, it has two methods that write to the value:
set(value)replaces the value.update(fn)computes a new value from the current one. It is the same asset(fn(currentValue)).
Neither method sends a request. They change only the copy of the data held in the browser. httpResource is also writable, with the same methods.
If you want to give other code read access without write access, call asReadonly(). It returns a Resource that has the same signals but no set or update.
The `local` status
When you call set() or update(), the resource moves to the local status. This status means the current value was written by your code and did not come from the loader.
| Status | Meaning | `value()` |
|---|---|---|
| `idle` | `params` returned `undefined`, so no load has started | `defaultValue` or `undefined` |
| `loading` | First load, or a load after `params` changed | previous value or default |
| `reloading` | A `reload()` is in progress | previous value |
| `resolved` | The loader finished successfully | loaded value |
| `local` | Your code wrote the value with `set` or `update` | the value you wrote |
| `error` | The loader failed | reading it throws |
isLoading() is true for loading and reloading. It is false for local.
The diagram leaves out one rule: set() can be called in any status. It always ends in local.
A first example
This is the todo list from the earlier chapter, with the template filled in.
import { Component, resource } from '@angular/core';
interface Todo {
id: number;
title: string;
}
@Component({
selector: 'app-todos',
template: `
<button (click)="refresh()">Refresh</button>
<button (click)="addLocal()">Add locally</button>
<p>Status: {{ todos.status() }}</p>
<ul>
@for (todo of todos.value(); track todo.id) {
<li>{{ todo.title }}</li>
}
</ul>
`,
})
export class TodosComponent {
readonly todos = resource({
defaultValue: [] as Todo[],
loader: async ({ abortSignal }) => {
const res = await fetch('/api/todos', { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Todo[];
},
});
refresh() {
this.todos.reload();
}
addLocal() {
this.todos.update((list) => [...list, { id: Date.now(), title: 'New todo' }]);
}
}After the first load the status shows resolved. Click "Add locally" and it changes to local, with one more item in the list. No request is sent. Click "Refresh" and the loader runs again. The server's answer replaces your local item, because the loader result always wins.
What overwrites a local value
A local value lasts only until the next load finishes. Two things start a load:
reload()runs the loader with the current params. Whatever it returns replaces the local value.- A change in
paramsstarts a new load. The local value belongs to the old params, so it is discarded when the new result arrives.
If you call set() while a load is in flight, the resource switches to local and cancels that load. The abortSignal passed to your loader fires, and the late response is ignored. So a user edit is not overwritten by a slower request that started before it.
If params returns undefined, the resource is idle. You can still call set() on it, and it will report local.
Writing the value correctly
Keep values immutable
set() compares the new value with the current one. If they are the same reference, nothing is notified. Mutating the array in place does not update the template:
// Wrong: same array reference, so dependents are not notified.
this.todos.update((list) => {
list.push({ id: 99, title: 'Lost' });
return list;
});
// Right: return a new array.
this.todos.update((list) => [...list, { id: 99, title: 'Kept' }]);Know what `update` receives
With a defaultValue, the callback receives the value type directly, as in the todo list above. Without one, the type is T | undefined, and you must handle undefined:
this.user.update((u) => (u ? { ...u, name: 'Ada' } : u));Do not update from the `error` status
In the error status, reading value() throws. update() reads the current value, so it throws too. Use set() to recover from an error, or guard with hasValue():
if (this.todos.hasValue()) {
this.todos.update((list) => list.slice(0, -1));
}hasValue() is also a type guard, so inside the if the value type no longer includes undefined.
Optimistic updates with rollback
A common use of set() is the optimistic update. You show the change at once, send it to the server, and undo it if the request fails. The pattern has four steps:
- Save the current value.
- Write the expected result with
set()orupdate(). - Send the request.
- On success, swap in the server's version. On failure, restore the saved value.
import { Component, resource, signal } from '@angular/core';
interface Todo {
id: number;
title: string;
}
@Component({
selector: 'app-todo-list',
template: `
<button (click)="add('Write tests')">Add</button>
@if (message()) {
<p>{{ message() }}</p>
}
<ul>
@for (todo of todos.value(); track todo.id) {
<li>{{ todo.title }}</li>
}
</ul>
`,
})
export class TodoListComponent {
readonly message = signal('');
readonly todos = resource({
defaultValue: [] as Todo[],
loader: async ({ abortSignal }) => {
const res = await fetch('/api/todos', { signal: abortSignal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as Todo[];
},
});
async add(title: string) {
const previous = this.todos.value();
const temp: Todo = { id: -Date.now(), title };
this.message.set('');
this.todos.set([...previous, temp]);
try {
const res = await fetch('/api/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const saved = (await res.json()) as Todo;
this.todos.update((list) => list.map((t) => (t.id === temp.id ? saved : t)));
} catch {
this.todos.set(previous);
this.message.set('Could not save the todo.');
}
}
}The temporary item has a negative id, so it cannot collide with a server id. After the response, update() replaces it with the saved record, which has the real id. The status stays local throughout. If you want the server to be the single source of truth afterwards, call this.todos.reload() at the end of the try block.
Edge cases in the rollback
- Concurrent edits. Restoring
previousalso removes any other local change made while the request was in flight. If users can add items quickly, undo only your own change. For example, filter out the item withtemp.idinstead of restoring the whole saved list. - A reload in between. If
reload()or a params change finishes while your POST is pending, the loader result replaces your temporary item. The laterupdate()then maps over a list that has notemp.id, so it changes nothing. The new item shows up only after the next load. Disable the button while a save is pending, or reload after the POST completes. - A failed rollback source. If the resource was in
errorwhen you tookprevious,this.todos.value()throws. CheckhasValue()first, or only offer the action when the list loaded.
Choosing between `set`, `update`, and `reload`
| Situation | Use |
|---|---|
| You have the full new value, such as a server response | `set(value)` |
| The new value is built from the old one, such as add, remove, or rename | `update(fn)` |
| You do not know what changed on the server | `reload()` |
| Different input should load different data | change the signal read in `params` |
Exercise
A resource with defaultValue: [] as Todo[] has status resolved. Your code calls todos.update(list => { list.push(newTodo); return list; }). The template does not change. Why, and what would you write instead?
Show answer
The callback returns the same array reference it received, so the resource sees no change and does not notify dependents. Return a new array instead: todos.update(list => [...list, newTodo]). After a correct update the status is local, and no request is sent.
Exercise
A user clicks "Add", which calls set() with a temporary item and starts a POST. Before the POST finishes, a reload() completes. What does the list show, and how do you avoid the problem?
Show answer
The loader result replaces the local value, so the temporary item disappears. When the POST finishes, update() finds no item with the temporary id and changes nothing. Avoid this by disabling actions while a save is pending, or by calling reload() after the POST completes so the new item comes from the server.