Anto Subash.

Table of contents

What is Fluxor

Fluxor is a zero boilerplate Flux/Redux library for .Net. The aim of Fluxor is to create a multi-UI, single-state store approach to front-end development without the headaches typically associated with other implementations, such as the overwhelming amount of boiler-plate code required just to add a very basic feature. Repo: https://github.com/mrpmorris/Fluxor Docs: https://github.com/mrpmorris/Fluxor/blob/master/Docs/README.md

When to use Fluxor

Fluxor uses Flux/Redux approach. It helps you to manage your app’s state in a single place and keep changes in your app more predictable and traceable. It makes it easier to manage the state. But all of these benefits come with tradeoffs and constraints. One might feel it adds up boilerplate code, making simple things a little overwhelming; but that depends upon the architecture decisions. If you are wondering if you need state management or not then you don't need it. When your app grows to the scale where managing app state becomes a hassle; and you start looking out for making it easy and simple. That is where you will find Fluxor helpful.

Creating Blazor Wasm project

1dotnet new blazorwasm -n FluxorWithBlazor

This will create a blazor wasm app.

Install Fluxor Packages

Install Nuget packages

1<PackageReference Include="Fluxor" Version="5.4.0" />
2<PackageReference Include="Fluxor.Blazor.Web" Version="5.4.0" />
3<PackageReference Include="Fluxor.Blazor.Web.ReduxDevTools" Version="5.4.0" />

Update the Program.cs

1using Fluxor;
2
3builder.Services.AddFluxor(o =>
4{
5    o.ScanAssemblies(typeof(Program).Assembly);
6    o.UseReduxDevTools(rdt =>
7      {
8          rdt.Name = "My application";
9      });
10});

Update the App.razor

1<Fluxor.Blazor.Web.StoreInitializer />

Now we are ready to create state in our Blazor application.

Fluxor Rules

  • State should always be read-only.
  • To alter state our app should dispatch an action.
  • Every reducer that processes the dispatched action type will create new state to reflect the old state combined with the changes expected for the action.
  • The UI then uses the new state to render its display.

Core Concepts (State, Actions, and Reducers)

State

Imagine your app’s state is described as a plain object. For example, the state of a counter app might look like this:

1[FeatureState]
2public class CounterState
3{
4  public int ClickCount { get; }
5
6  public CounterState(int clickCount)
7  {
8    ClickCount = clickCount;
9  }
10}

This object is like a “model” except that there are no setters. This is so that different parts of the code can’t change the state arbitrarily, causing hard-to-reproduce bugs. To change something in the state, you need to dispatch an action.

Action

An action is a plain c# object (notice how we don’t introduce any magic?) that describes what happened. Here are a few example actions:

1public class IncrementCounterAction
2{
3}

Enforcing that every change is described as an action lets us have a clear understanding of what’s going on in the app. If something changed, we know why it changed. Actions are like breadcrumbs of what has happened.

Reducers

Finally, to tie state and actions together, we write a function called a reducer. Again, nothing magical about it—it’s just a function that takes state and action as arguments, and returns the next state of the app. It would be hard to write such a function for a big app, so we write smaller functions managing parts of the state:

1public static class Reducers
2{
3    [ReducerMethod]
4    public static CounterState ReduceIncrementCounterAction(CounterState state, IncrementCounterAction action) =>
5        new(clickCount: state.ClickCount + 1);
6}

Using the State

To use the state management we will update the counter page which comes with the default app.

1@page "/counter"
2@using FluxorWithBlazor.State.Counter
3@inject IDispatcher dispatcher
4@inject IState<CounterState> counterState
5<PageTitle>Counter</PageTitle>
6
7<h1>Counter</h1>
8
9<p role="status">Current count: @counterState.Value.ClickCount</p>
10
11<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
12
13@code {
14    private void IncrementCount()
15    {
16        dispatcher.Dispatch(new IncrementCounterAction());
17    }
18}

In the IncrementCount method we are dispatching an action and the current count is displayed buy injecting the state.

Effects

Flux state is supposed to be immutable, and that state replaced only by pure functions, which should only take input from their parameters. With this in mind, we need something that will enable us to access other sources of data such as web services, and then reduce the results into our state. That is where the effects comes in. Effect handlers cannot (and should not) affect state directly. They are triggered when the action they are interested in is dispatched through the store, and as a response they can dispatch new actions.

Fetch data with effects

We will update the fetch data sample provided in the default blazor application with Effects.

Fetch data action

Lets create a action which will initiate the action. this will the be a empty action which will be used to trigger the effect.

1public class FetchDataAction
2{
3}

Fetch data result action

Once the data is received from the server we need a action to update the state. we will use the ´FetchDataResultAction´ for that. It will have a the list of Weather forecast available.

1public class FetchDataResultAction
2{
3    public IEnumerable<WeatherForecast> Forecasts { get; }
4
5    public FetchDataResultAction(IEnumerable<WeatherForecast> forecasts)
6    {
7        Forecasts = forecasts;
8    }
9}

Weather state

Weather state will the two property ´Forecasts´ and ´IsLoading´.

1[FeatureState]
2public class WeatherState
3{
4  public bool IsLoading { get; }
5  public IEnumerable<WeatherForecast> Forecasts { get; }
6
7  private WeatherState() { }
8  public WeatherState(bool isLoading, IEnumerable<WeatherForecast> forecasts)
9  {
10    IsLoading = isLoading;
11    Forecasts = forecasts ?? Array.Empty<WeatherForecast>();
12  }
13}

Weather Reducers

In the reducer we need to manage 2 action which are created by us. One is to trigger the data fetch and the next one is to handle the data result.

1public static class Reducers
2{
3  [ReducerMethod]
4  public static WeatherState ReduceFetchDataAction(WeatherState state, FetchDataAction action) =>
5    new(isLoading: true, forecasts: null);
6
7  [ReducerMethod]
8  public static WeatherState ReduceFetchDataResultAction(WeatherState state, FetchDataResultAction action) =>
9    new(isLoading: false, forecasts: action.Forecasts);
10}

Weather effects

Effects is where we will make our ´http´ call. We will inject the ´HttpClient´ and use that in the effect method. once the call is successful we will dispatch an action with the data result.

1public class Effects
2{
3    private readonly HttpClient Http;
4
5    public Effects(HttpClient http)
6    {
7        Http = http;
8    }
9
10    [EffectMethod]
11    public async Task HandleFetchDataAction(FetchDataAction action, IDispatcher dispatcher)
12    {
13        var forecasts = await Http.GetFromJsonAsync<WeatherForecast[]>("sample-data/weather.json");
14        if(forecasts is not null)
15        {
16            dispatcher.Dispatch(new FetchDataResultAction(forecasts: forecasts!));
17        }
18    }
19}

Update the fetch data page

We need to update the fetch data page to use the weather state.

1@page "/fetchdata"
2@inject IDispatcher dispatcher
3@inject IState<WeatherState> weather
4@inherits Fluxor.Blazor.Web.Components.FluxorComponent
5<PageTitle>Weather forecast</PageTitle>
6
7<h1>Weather forecast</h1>
8
9<p>This component demonstrates fetching data from the server.</p>
10
11@if (weather.Value.IsLoading)
12{
13	<p><em>Loading...</em></p>
14}
15else
16{
17	<table class="table">
18		<thead>
19			<tr>
20				<th>Date</th>
21				<th>Temp. (C)</th>
22				<th>Temp. (F)</th>
23				<th>Summary</th>
24			</tr>
25		</thead>
26		<tbody>
27			@foreach (var forecast in weather.Value.Forecasts)
28			{
29			<tr>
30				<td>@forecast.Date.ToShortDateString()</td>
31				<td>@forecast.TemperatureC</td>
32				<td>@forecast.TemperatureF</td>
33				<td>@forecast.Summary</td>
34			</tr>
35			}
36		</tbody>
37	</table>
38}
39
40@code {
41
42	protected override void OnInitialized()
43	{
44		base.OnInitialized();
45		dispatcher.Dispatch(new FetchDataAction());
46	}
47}

Repo : https://github.com/antosubash/blazor-state-management-with-fluxor

Buy Me a Coffee at ko-fi.com