How to Maintain State in the Blazor ListBox Using Fluxor?
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (181).NET Core  (28).NET MAUI  (228)Angular  (113)ASP.NET  (49)ASP.NET Core  (81)ASP.NET MVC  (87)Azure  (42)Black Friday Deal  (1)Blazor  (238)BoldSign  (14)DocIO  (24)Essential JS 2  (110)Essential Studio  (201)File Formats  (74)Flutter  (137)JavaScript  (226)Microsoft  (122)PDF  (83)Python  (1)React  (105)Streamlit  (1)Succinctly series  (131)Syncfusion  (970)TypeScript  (33)Uno Platform  (3)UWP  (3)Vue  (46)Webinar  (53)Windows Forms  (59)WinUI  (72)WPF  (163)Xamarin  (159)XlsIO  (38)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (11)Business intelligence  (55)Button  (4)C#  (164)Chart  (149)Chart of the week  (59)Cloud  (15)Company  (440)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (73)Development  (683)Doc  (7)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (7)Essential Tools  (13)Excel  (43)Extensions  (23)File Manager  (7)Gantt  (21)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (522)Mobile MVC  (9)OLAP server  (2)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (45)Performance  (13)PHP  (2)PivotGrid  (5)Predictive Analytics  (6)Report Server  (3)Reporting  (8)Reporting / Back Office  (9)Rich Text Editor  (12)Road Map  (12)Scheduler  (54)Security  (5)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (32)Solution Services  (4)Spreadsheet  (11)SQL  (15)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (409)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (630)What's new  (345)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
How to Maintain State in the Blazor ListBox Using Fluxor

How to Maintain State in the Blazor ListBox Using Fluxor?

TL;DR: Learn how to maintain state in the Syncfusion Blazor ListBox using the Fluxor state management library. This guide covers setting up Fluxor, integrating it with the ListBox, and managing selected items for a smooth user experience. 

The Syncfusion Blazor ListBox is a feature-rich component that provides excellent functionalities rather than just displaying a list of items. It allows users to select one or more items using check boxes, with a mouse, or through keyboard interactions. It can be populated using an array of strings or objects.

The Fluxor is a state management library heavily inspired by the Flux architecture and popularized by Facebook’s React library. It provides a predictable and efficient way to manage your app’s state by enforcing unidirectional data flow and promoting a reactive programming style.

In this blog, we’ll learn how to maintain the state in the Syncfusion Blazor ListBox using Fluxor. We’ll store the selected items (current state) of the ListBox, i.e., the selected item values, in the Fluxor. Then, we’ll load the values from the Fluxor and display them at the end of the ListBox while scrolling through a huge volume of items. This will provide a smooth navigation and user experience.

Getting started with Blazor ListBox

First, refer to the getting started with Blazor ListBox component documentation.

Now, refer to the following code example demonstrating how to render a ListBox component in a Razor page.

@using Syncfusion.Blazor.DropDowns

<SfListBox TValue="string[]" DataSource="@Vehicles" TItem="VehicleData">
 <ListBoxFieldSettings Text="Text" Value="Id" />
</SfListBox>
@code {
    public string[] value = new string[] { “Vehicle-01” };
    public List<VehicleData> Vehicles = new List<VehicleData> {
        new VehicleData { Text = "Hennessey Venom", Id = "Vehicle-01" },
        new VehicleData { Text = "Bugatti Chiron", Id = "Vehicle-02" },
        new VehicleData { Text = "Bugatti Veyron Super Sport", Id = "Vehicle-03" }
    };

    public class VehicleData {
      public string Text  { get; set; }
      public string Id  { get; set; }
    }
}

Getting started with Fluxor

Fluxor helps you manage the state of your app in a predictable and organized manner. Follow these steps to get started with it:

Step 1: Installation

To add the Fluxor NuGet package to your Blazor server project, use the following command in the Package Manager Console window.

Install-Package Fluxor.Blazor.Web

Step 2: Register the store

Add the following code to your App.razor file. This code is an essential setup for Fluxor state management in your Blazor app. It initializes the Fluxor store and ensures your app can manage state and actions effectively.

<Fluxor.Blazor.Web.StoreInitializer />

Step 3: Register the Fluxor

To integrate Fluxor into your Blazor app, navigate to the Program.cs file. Inside the Main method, add the following code to register Fluxor.

builder.Services.AddFluxor(options => 
{
    options.ScanAssemblies(typeof(Program).Assembly);
});

This registration ensures Fluxor is properly integrated, allowing efficient state management throughout your app.

Step 4: Set up the feature/state

Now, create a Store folder within your project, and inside it, create a subfolder named ValueUseCase. Add a new class called ValueState.cs within this subfolder.

Refer to the following code example.

using Fluxor;

namespace SyncfusionBlazorApp.Store.ValueUseCase 
{
    [FeatureState]
    public record ValueState(string[] Items) 
    {
        public ValueState() : this(new string[0]) 
        {
            //default constructor
        }
    }
}

Step 5: Defining actions

Create an action class named SetValueAction to update items from the  Blazor ListBox in the Store folder. In the following code example, we’ll define the following two records within the SyncfusionBlazorApp.Store namespace. These records are used to manage actions and states within a Blazor app.

  • EventValueClicked: It accepts an array of strings, likely conveying a list of items or values, and it is typically dispatched to trigger state updates within a state management system.
  • SetValueAction: It also takes an array of strings as its input parameter and updates the application’s state.

Refer to the following code example.

using SyncfusionBlazorApp.Store.ValueUseCase;
namespace SyncfusionBlazorApp.Store
{
    public record EventValueClicked(string[] Items);
    public record SetValueAction(string[] Items);
}

Step 6: Defining reducers

To manage state changes effectively in a Fluxor-based app, create a Reducer.cs class within the ValueUseCase folder. This class will contain ReduceSetValueItem, specifically designed to handle state changes when the SetValueAction is dispatched.

Refer to the following code example. When the SetValueAction is triggered, the ReduceSetValueItem method generates a new state object. This new state object’s Items property is updated with the values provided in the action. This process ensures that the state is kept up to date in a predictable and immutable manner, following a common pattern in Fluxor-based state management.

using Fluxor;

namespace SyncfusionBlazorApp.Store.ValueUseCase
{
    public class Reducers 
{ [ReducerMethod] public static ValueState ReduceSetValueItem(ValueState state, SetValueAction action)
{ return state with { Items = action.Items }; } } }

Step 7 Defining effects

In the ValueUseCase folder, let’s create an Effects.cs class to handle effects. Within this class, we’ll define the HandleEventCounterClicked method, which listens for EventValueClicked actions. Upon detection, it dispatches a SetValueAction to update the application’s state potentially.

Refer to the following code example.

using Fluxor;

namespace SyncfusionBlazorApp.Store.ValueUseCase 
{
    public class Effects 
{ private readonly IState<ValueState> _valueState; public Effects(IState<ValueState> valueState)
{ _valueState = valueState; } [EffectMethod] public Task HandleEventCounterClicked(EventValueClicked action, IDispatcher dispatcher)
{ dispatcher.Dispatch(new SetValueAction(action.Items)); return Task.CompletedTask; } } }

Step 8: Integrate Fluxor in the Blazor ListBox component

Now, connect the Fluxor state to your ListBox component’s Value property. Then, trigger the dispatch of the SetItemsAction within the ValueChange event of the ListBox.

This ensures that whenever there is a change in the selection of the ListBox, an update is automatically initiated in the Fluxor state, guaranteeing synchronization between the UI and the application state.

Refer to the following code example.

@page "/"
@using Syncfusion.Blazor.DropDowns
@using Fluxor
@using SyncfusionBlazorApp.Store;
@using SyncfusionBlazorApp.Store.ValueUseCase
<SfListBox TValue="string[]" Value="@valueState.Value.Items" DataSource="@Vehicles" TItem="VehicleData">
 <ListBoxFieldSettings Text="Text" Value="Id" />
 <ListBoxEvents TValue="string[]" TItem="VehicleData" ValueChange="@valueChange"></ListBoxEvents>
</SfListBox>
<span><b>Selected Items</b></span>
<ol>
    @foreach (var item in valueState!.Value.Items) 
    {
        <li>@item</li>
    }
</ol>
@code {
    [Inject]
    private IDispatcher? dispatcher { get; set; }
    [Inject]
    protected IState<ValueState>? valueState { get; set; }
    public List<VehicleData> Vehicles = new List<VehicleData> {
        new VehicleData { Text = "Hennessey Venom", Id = "Vehicle-01" },
        new VehicleData { Text = "Bugatti Chiron", Id = "Vehicle-02" },
        new VehicleData { Text = "Bugatti Veyron Sport", Id = "Vehicle-03" },
        new VehicleData { Text = "SSC Ultimate Aero", Id = "Vehicle-04" },
        new VehicleData { Text = "Koenigsegg CCR", Id = "Vehicle-05" },
        new VehicleData { Text = "McLaren F1", Id = "Vehicle-06" },
        new VehicleData { Text = "Aston Martin One- 77", Id = "Vehicle-07" },
        new VehicleData { Text = "Jaguar XJ220", Id = "Vehicle-08" }
    };
    private void valueChange(ListBoxChangeEventArgs<string[], VehicleData> args)
    {
        dispatcher?.Dispatch(new EventValueClicked(args.Value));
    }
    public class VehicleData {
        public string Text  { get; set; }
        public string Id  { get; set; }
    }
}

After executing the above code examples, we will get the output in the following image.

Maintaining state in Blazor ListBox component using Fluxor
Maintaining state in Blazor ListBox component using Fluxor

GitHub reference

For more details, refer to state management in Blazor ListBox using the Fluxor GitHub demo.

Conclusion

Thanks for reading! In this blog, we’ve seen how to maintain the state in the Syncfusion Blazor ListBox component using Fluxor. Try out the steps discussed in this blog, and leave our feedback in the comments section below!

Our existing customers can download the new version of Essential Studio from the License and Downloads page. If you are not a Syncfusion customer, try our 30-day free trial to check out our incredible features.

If you have any questions or need assistance, our support team is always here to help. Feel free to contact us through our support forumsupport portal, or feedback portal. We look forward to hearing from you!

Related blog

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed