5

I'm making a Blazor Server Side project and I wanted to make a button that desactivate after a click, but without using the disabled attribute of <button>. The code is pretty simple :

@functions {

    LogInForm logInForm = new LogInForm();
    bool IsDisabled;
    SignInResult result;

    protected override void OnInitialized()
    {
        IsDisabled = false;
    }

    async Task TryLogIn()
    {
        IsDisabled = true;
        StateHasChanged();
        result =  await _LogInService.TryLogIn(logInForm);
        Console.WriteLine("Logging status : " + (result.Succeeded ? "Sucess" : "Failure"));
        IsDisabled = false;
        StateHasChanged();
    }

}

For odd reasons, the first StateHasChanged isn't triggering but the second does re-render the page. It can be quite easily testes by going in Debug mode and entering into the StateHasChanged() method. On second time call it does stop on the HTML code after going into the method but not the first time.

Why so ?

NB : I'm not looking for any workaround using Task.Delay or Task.Run(...) only, as it exist a race condition between those threads and the UI refresh thread, and so it is not a reliable solution. I'm looking for answers on the StateHasChanged() behaviour or a workaround by using events like PropertyChanged or EventCallback and putting the button as a child component.

Edit : After some testing, it seems that StateHasChanged() only triggers the re-render of the component after an await operation on a Task. It can be easily tested by putting in commentary the result = await _LogInService.TryLogIn(logInForm); line or changing IsDisabled = ... to await new Task.Run(() => { IsDisabled = ...}). I have some workaround now, but I still wonder why this is a feature. Shouldn't StateHasChanged() re-render after any operations ? Or it consider that only async operations (so mostly server-calls) can change something in the UI ?

6
  • Does this answer your question? Blazor - Display wait or spinner on API call Commented Nov 19, 2019 at 11:52
  • No, because it seems your answer relies on the Task.Delay(1) workaround only, which, has said in the Nota Bene, isn't reliable due to race condition. Beside, I'm more asking an answer on how StateHasChanged() works or how to do it by using events works more than having a workaround. Commented Nov 19, 2019 at 11:56
  • It's the good old DoEvents() problem in a new disguise. Commented Nov 19, 2019 at 14:31
  • The real problem is probably with _service.TryLogIn(), is it really async? Or just pretending? Commented Nov 19, 2019 at 14:32
  • No, TryLogIn() isn't a fake async as it uses a SignInManager to check and sign in the user. Commented Nov 19, 2019 at 14:36

2 Answers 2

7

The Blazor team is about to publish documentation about how StateHasChanged() works.

You can track it here here: https://github.com/aspnet/AspNetCore/issues/14591

For the time being, I think this explanation taken from a github comment is an excellent explanation:

Adding a call to StateHasChanged simply queues the component to be rendered. The renderer decides when the renders happen.

This can be triggered by 4 circumstances:

  • Initial render where the bootstrap process triggers the initial render of the root component and all its children.
  • An event, in which the component that handles the event automatically triggers a new render after the event, and potentially its children if it renders new children or change their parameters.
  • As a result of calling StateHasChanged from an InvokeAsync call (marshalling back into the UI thread, essentially)
  • As a result of the parent component changing the parameters for the child component, which happens as part of the diffing process when the renderer calls SetParametersAsync on the child component.

To be very clear, calling StateHasChanged only queues a Render for the component or "marks it as dirty".

It's the renderer the one that decides when and how to produce the renders. BuildRenderTree does not result in new rendered output, only in a new definition of the "V-DOM" for the component at the time it's being called.

Normally, a component gets rendered once per render batch (which is a collection of components that are rendered/diffed together and sent to the UI for update). There are only two situations in which a component renders more than once in a batch:

  • You have a component that directly implements IComponent and calls RenderHandle.Render
  • You have a circular dependency between a child and a parent component that might cause a parent to re-render as part of a children invoking some callback parameter from the parent as part of its initialization

Source: https://github.com/aspnet/AspNetCore/issues/15175#issuecomment-544890549

1
  • 1
    This is a really good explanation, thanks. So I should use events then to "properly" trigger the re-render ? I'm still new to this, specially into event programming, so I'm trying to understand how to use them. Commented Nov 19, 2019 at 12:22
4

The following is the flow of execution to describe how re-rendering occurs:

  1. Parent component calls StateHasChanged
  2. A new render tree is produced
  3. The diff between the old tree and the new tree is happening
  4. The values being passed to your child component are considered different to the ones it currently hold.
  5. SetParameters is being called on the child component to update them with the values the parent passed to it.

Now, when you call StateHasChanged after assigning a value to the local variable IsDisabled, does not really change the state of the component, and there is no reason why calling StateHasChanged will yield a re-rendering. When you call StateHasChanged, it simply queues a render request for that component. But there is no reason for re-rendering...

Or it consider that only async operations (so mostly server-calls) can change something in the UI ?

It has nothing to do whether the type of the operation is async or not, except of the OnInitializedAsync method, in which case, the StateHasChanged method is automatically called when the OnInitializedAsync method completes to re-render the UI once again, with the new data retrieved by the async calls perform in the OnInitializedAsync method.

Update:

What you want can be done in various ways, the simplest of which is demonstrated here:

   <input type="button" value="Click me now"  disabled="@IsDisabled" @onclick="TryLogIn" />


@code{ 

    bool IsDisabled;

    protected override void OnInitialized()
    {
        IsDisabled = false;
    }

    async Task TryLogIn()
    {
        IsDisabled = true;

        // Do some async work here...
        // Note: Replace your async method with Task.Delay 
        await Task.Delay(5000);

        IsDisabled = false;

    }

}

This should work... Note: The only way you can disable your button control is by using the disabled property

No need to call the StateHasChanged method. It is automatically called by the code the compiler insert into your source code when it (the compiler) creates an EventCallback 'delegate' for your component.

The StateHasChanged method is automatically called after a UI event is triggered.

6
  • Thanks for you answer ! So how could we define the state of a component then, if not all the variables it holds ? Commented Nov 19, 2019 at 12:04
  • I agree with you that variables such as the local variable IsDisabled may describe the state of the component, but not one that requires re-rendering. Assigning a new value to such a local variable, I think, may be considered as modifying the variable "state", but not really one that modify the component itself, and requires re-rendering.
    – enet
    Commented Nov 19, 2019 at 12:25
  • Ok so the state is only defined by the parameters of a componant then. So which method is the "proper" method to do what I want ? Transforming the button into a component and modifiying its parameter, setting events handlers into a single component or into the parent and his childs ? Commented Nov 19, 2019 at 12:32
  • Thanks again for the answer. I wasn't using the disabled attribute because i read that it could be disabled by an end-user and so I wanted to make my button secure. Seems like learning Blazor isn't difficult but learning elements are kind of scattered everywhere and Microsoft documentation can be incomplete or feel obscure for a beginer as blazor is kind of new . I'll stick with either your solution or my workaround for now and I'll study how to do it more properly, so in the end I can have a SubmitButton component with the behavior wanted. I'll mark your answer as accepted for now. Commented Nov 19, 2019 at 13:39
  • 1
    The reasoning to not use the disabled attribute is crooked, and has nothing to do with reality. Every thing in the web can be tampered with, and wanting to make your button secure is a bad idea. Security is always implemented on the server, not on the client, and if we apply some measurements, they are intended only for UI purposes, as for instance the use of the AuthorizeView component in Blazor WebAssembly...
    – enet
    Commented Nov 19, 2019 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.