Data access by render mode
A page that runs on the server can read your database. A page that runs in the browser can't, so it calls an API. The page's render mode decides which. If your pages load data through an interface, the same page works in both places.
One interface for every mode
Put the queries behind an interface, a store, and have the page ask it. The page doesn't know where the store gets its rows:
public interface ICustomerStore
{
Task<IReadOnlyList<CustomerRow>> ListAsync(CancellationToken cancellationToken = default);
Task<CustomerRow?> GetAsync(int id, CancellationToken cancellationToken = default);
}
public sealed record CustomerRow(int Id, string Name, string City); "/customers"
ICustomerStore Customers
<Table Items="_customers">
<Columns>
<PropertyColumn Property="c => c.Name" />
<PropertyColumn Property="c => c.City" />
</Columns>
</Table>
{
private IReadOnlyList<CustomerRow> _customers = [];
protected override async Task OnInitializedAsync() => _customers = await Customers.ListAsync();
}The render mode decides which class answers. There are four render modes and two places a page runs, so there are two classes to write at most.
What each render mode needs
| Render mode | The page runs | What answers the interface |
|---|---|---|
| Static | On the server | A store over your DbContext |
| Interactive Server | On the server, for as long as its circuit | The same store, with a context for each call |
| WebAssembly | In the browser, after prerendering on the server | A client store that calls your endpoints, and the server’s store while prerendering |
| Auto | On the server on the first visit, in the browser on later ones | Both stores, each registered in its own project |
- Data access on the server: the store for Static and Interactive Server pages.
- Data access in the browser: the client store, its endpoints and their checks, for WebAssembly and Auto pages.
Which pattern an app needs
| The app's pages | What to build |
|---|---|
| Static, Interactive Server, or both | A store over your DbContext. No API. |
| Mostly static, with a few pages in the browser | The same store, plus endpoints and a client store for the data those few pages use. |
| WebAssembly or Auto throughout | Endpoints and a client store for all of the app's data. |
Use the interface in a server-only app too. To move a page to the browser later, you add a client store and its endpoints, and the page doesn't change.
Next steps
- Render modes: what each render mode is, and how to choose one for a page.
- What each render mode adds: this page counted in each render mode.
- Data from an API: a grid's sort, filters and paging over HTTP, and what the server limits.