January 1, 0001 · 2 minute read

Consider a refactor

Notice in this example we use an If statement to determine whether to show or hide parts of the UI.

@if (Id is > 0)
{
    <article>
        <h2>Details for user @Id</h2>
    </article>
}
else
{
    <article>
        <h2>Contacts</h2>
        <a href="/contacts/1">Alice Krige</a>
    </article>
}

This actually gives us another option for loading data when navigation changes occur.

We could refactor the markup for the contact details into a separate component, which fetches its own data.

Now with this example we’ve a handy Contact component which does the heavy lifting of fetching the contact details and displaying them.

But what happens when we navigate to a contact now?

Because we’re removing/adding this component in response to whether or not an Id is set, we might get away with using OnInitialized here.

If we navigate from ‘/contacts’ to ‘/contacts/1’ Blazor will spot the Id parameter, hide the contacts list, display the contact component (for Alice Krige) and initialize it at that point.

Here it is in action:

However, this only works if we remove and add the component.

Here’s another example where, instead of adding/removing the contact component we leave it visible next to the contact list.

Try navigating between contacts now and you’ll see we’re back to our stale data problem.

Whichever contact you navigate to first is the one you’re stuck with if you then attempt to select a different contact from that same page.

Join the Practical ASP.NET Newsletter

Ship better Blazor apps, faster. One practical tip every Tuesday.

I respect your email privacy. Unsubscribe with one click.