Previous data
After an action, the loaders run again to load the changed data. Often the action only changed a small part of that data, like marking one todo as done. When the action returns what it changed, a loader can update the data it loaded before, instead of loading everything again.
The loader gets the result of the action as the action argument, and the data it returned the last time as the previous argument.
previous is a promise, so the loader awaits it.
let Router = Routes(
<App>
<Todos path="todos" loader={todosLoader} action={todosAction} />
</App>,
);
async function todosAction({ data }) {
let id = Number(data.get('id'));
let done = data.get('done') === 'true';
await fetch(`/api/todos/${id}`, {
method: 'PATCH',
body: JSON.stringify({ done }),
});
return { todo: { id, done } };
}
async function todosLoader({ action, previous }) {
if (action?.todo) {
let todos = await previous;
if (todos) {
return todos.map((todo) =>
todo.id === action.todo.id ? { ...todo, ...action.todo } : todo,
);
}
}
return fetch('/api/todos.json');
}
When there is no previous data, like on the first load, previous resolves to undefined and the loader loads all todos.
Any other action, like creating or deleting a todo, does not return a todo, so the loader also loads all todos again.
With a server api, the loader can use server to load the data from the server instead.
async function todosLoader({ action, previous, server }) {
if (action?.todo) {
let todos = await previous;
if (todos) {
return todos.map((todo) =>
todo.id === action.todo.id ? { ...todo, ...action.todo } : todo,
);
}
}
return server();
}