2

I am developing a Blazor app and in this app, I need to store the state of a List of user-selected Items. when the user presses the 'Save Changes' button I would like to store the list in the state.

So far I have written the four mandatory classes that are written in the Fluxor doc:

ServiceState:

public record ServiceState
{
    public List<ServiceModel> SelectedService { get; init; }
}

ServiceFeature

public override string GetName() => nameof(ServiceState);


    protected override ServiceState GetInitialState() 
    {
        return new ServiceState
        {
            SelectedService = new List<ServiceModel>()
        };
    } 

SelectServiceAction:

public class SelectServiceAction
{
    public List<ServiceModel> _serviceList;

    public SelectServiceAction(List<ServiceModel> choosenServices)
    {
        _serviceList = choosenServices;
    }
}

and SelectServiceReducer:

public class SelectServiceReducer
{
    [ReducerMethod]
    public static ServiceState OnSelectService(ServiceState state, SelectServiceAction action) 
    {

        return state with
        {
            SelectedService = action._serviceList
        };
    }
    
}

I have tried many things and nothing seems to work the List stored in the state appears always empty but the funny thing is that in the SelectServiceAction class:

public SelectServiceAction(List<ServiceModel> choosenServices)
{
    _serviceList = choosenServices;
}

if I put a breakpoint in the last } _serviceList contains correctly all the items that were contained in the list I passed to the dispatcher. It seems like the problem is in the ServiceState itself,

Do you happen to know what am I doing wrong? If you need me to show more code, I will post it I thank you kindly in advance.

andreacode
  • 21
  • 1

1 Answers1

0

I found a way to do this. I don't know if this is the best way but here we are.

Your SelectServiceAction should have a ServiceModel in the constructor. I also changed the name of your method. I think its good to place the verb in the method name because you're likely to have a remove as well.

public class SelectServiceAddAction 
{
    public ServiceModel _service {get; set; }
    public SelectServiceAddAction(ServiceModel service)
     {
         _service = service;
     }
}

then in your reducer you call the method.

public static class SelectServiceReducer
{ 
     [ReducerMethod]
     public static ServiceState OnSelectService(ServiceState state, SelectServiceAddAction action)
     {
       var SelectedService = state.SelectedService;
       SelectedService.Add(action._service);
       return state with 
       {
         SelectedService = SelectedService
       };
     }
}

Also consider changing "SelectedService" to a name that involves the state such as "CurrentSelectedServices" hope this helps!

odus
  • 48
  • 8