Async and server communication

In this chapter we will use axios - a popular HTTP client.

To use it, open command line in the root of the project (where package.json is located) and type:

npm install --save axios

Stop and rerun the project with dotnet run.

ASP.NET Core API controllers

ASP.NET Core doesn't have different namespaces or base classes for MVC and API. Instead, all controllers simply inherit Microsoft.AspNetCore.Mvc.Controller class and return either a view or data.

Simple controller with no action is implemented as:

[Route("api/[controller]")]
public class MoviesController : Controller
{
}

Notice that the route gives us /api/movies prefix for all actions.

Simple GET action can be defined as:

[HttpGet]
public IEnumerable<Movie> GetAllMovies()
{
    return new[]
    {
        new Movie {
            Id =  1,
            IsWatched =  true,
            Title =  "Matrix 1"
        },
        // ...
    };
}

Navigate to http://localhost:5000/api/movies to see the expected JSON output

Consuming API in client

axios is promised based which means that it is asynchronous by default. Promise<T> in ECMAScript is similar to Task<T> in C# world.

Once you have a promise, you can chain the next steps on it using the then method and finally catch errors using catch method.

Example:

axios.get('/api/sampledata')
    .then(r => {
        // r is a HTTP response
        // r.data is the data from web
        // service already deserialized into object
        let data = r.data
    })
    .catch(e => {
        // handle errors, usually this is the last chain link
    })

Using it inside react is quite easy, just call setState in then and/or catch methods.

async-await

Using then and catch forces us to write smaller callbacks and use fluent style. Typescript (and future versions of ECMAScript) offer C#-like syntax for writing async code.

async function getSampleDataAsync() {
    let data = await axios.get('/api/sampledata')
}

results matching ""

    No results matching ""