0

My Blazor component looks like this:

<input type="text" @bind-value="@MyText" @bind-value:event="oninput" />

@code {
    private String myText;
    protected String MyText
    {
        get { return myText; }
        set
        {
            myText = value;
            //await GetMyHttp();
        }
    }
    private async Task GetMyHttp()
    {
        HttpClient Http = _httpClientFactory.CreateClient("MyId");
        myData = await Http.GetFromJsonAsync<MyData>("MyParams");
    }
}

And this works fine. But if I uncomment the await GetMyHttp(); line,
I get this compilation error:
Error CS4033 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.

How do I refactor this code to await the async method when the user types in the text box?

Hal Heinrich
  • 544
  • 1
  • 4
  • 21
  • Using `async` methods in a `get set` makes me very uncomfortable. I would rather just use the `async` method directly as the Handler for the input events, and drop the two-way binding. – Bennyboy1973 May 09 '22 at 03:24
  • Take a look at this Q&A that also includes Debounce and throttling https://stackoverflow.com/questions/57533970/blazor-textfield-oninput-user-typing-delay – dani herrera May 09 '22 at 06:44
  • Async properties are not allowed - See article by Stephen Cleary of Microsoft which covers the subject - https://blog.stephencleary.com/2013/01/async-oop-3-properties.html. You don't really show enough code to answer the question of how to code your requirement. Where does the Http Get fit in and what is mydata? @Enet's answer is very similar to mine taking your code in isolation. – MrC aka Shaun Curtis May 09 '22 at 13:27

1 Answers1

-3

You can have your MyText property getter and setter like this

protected String MyText
{
    get => myText;
    set
    {
        myText = value;
        Task.Run(()=> GetMyHttp());
    }
}

Alternatively you can hook into component's SetParametersAsync lifecycle event which will be called automatically when parameters are set for component, it will call GetMyHttp only if value of MyText is changed

public override async Task SetParametersAsync(ParameterView parameters)
    {
        if (parameters.TryGetValue<string>("MyText", out var value))
        {
            if (value != MyText)
            {
                await GetMyHttp();
            }
        }

        await base.SetParametersAsync(parameters);
    }
Surinder Singh
  • 1,165
  • 1
  • 3
  • 11