C#C
C#3y ago
49 replies
🔹

❔ Blazor .NET 8 RenderModeInteractiveAuto - fetch data via API

Blazor WASM: use HttpClient to call service (co-hosted or external)
Blazor Server: interactivity invokes code on server, virtual DOM, blah blah

Ok so how do I write a component that can fetch data for both modes?

Component authors should avoid coupling a component's implementation to a specific render mode. Instead, component authors should typically design components to support any render mode or hosting model...
https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-modes?view=aspnetcore-8.0

two ideas:
1. read some static property at runtime to determine the mode (or a hacky equivalent of this)
Good: doesn't couple component to a dependency
Bad: doing control flow like this means some path will always be unused in a component, looks kinda hacky and probably bug prone
2. inject an interface instead to do data fetching into a component, one with a server concrete implementation and a client concrete implementation, and register the client service in the wasm Client project and the server service in the Server project
Good: seems like the "right" way to do it
Bad: couples to an interface (not a huge problem since im not a component library author and still I imagine component library authors don't need to have a concrete fetch from web api impl that often).

im gonna jump in and try #2 but i thought i'd ask first because I thought I'd see this in docs or a sample or something, but the samples still just have hardcoded data
Learn about Blazor render modes and how to apply them in Blazor Web Apps.
ASP.NET Core Blazor render modes
Was this page helpful?