Instantly Update a Real-Time Chart with SignalR in Blazor Server-Side App
Tags: blazor, chart, webdev, ui
Published: 2023-02-08 14:04:18

---
title: Instantly Update a Real-Time Chart with SignalR in Blazor Server-Side App
published: true
date: 2023-02-08 11:30:00 UTC
tags: blazor, chart, webdev, ui
canonical_url: https://www.syncfusion.com/blogs/post/instantly-update-a-real-time-chart-with-signalr-in-blazor-server-side-app.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hsee1q353mt2aouokn8u.png
---
In this blog, we will learn how to create and update a real-time chart in a Blazor server-side app using SignalR communication.

## What is SignalR?

[SignalR](https://learn.microsoft.com/en-us/aspnet/signalr/overview/getting-started/introduction-to-signalr "SignalR documentation") is an open-source software library used to send asynchronous notifications to client-side applications. The library includes both server-side and client-side components.

SignalR works great in any kind of web app, but the best use cases are generally apps that need dynamically changing real-time data to be presented in the UI.

We are going to create a real-time chart in a Blazor server-side app using the [Syncfusion Blazor Charts component](https://www.syncfusion.com/blazor-components/blazor-charts "Syncfusion Blazor Charts Component") and SignalR.

## Prerequisites

- [.NET Core 6.0 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/6.0 ".NET Core 6.0").
- [Visual Studio 2022](https://visualstudio.microsoft.com/vs/ "Visual Studio 2022").

## Create a Blazor server-side app

Follow these steps to create a Blazor server-side application:

1. Open **Visual Studio** and select **create a new project**.
2. Then, select the **Blazor Server App** template and click **Next**.
3. Name the project **BlazorSignalRChartApp** and click **Next**. Ensure the target framework is **.NET 6.0**.
4. Finally, select **Create**.

Thus, we have created the Blazor server-side app.

## Setting up SignalR in the Blazor server project

Let’s configure the SignalR communication library with the Blazor server-side app.

### Step 1: Add SignalR client library.

Add the SignalR client library to the Blazor server-side project:

1. In the **Solution Explorer** window, right-click the **BlazorSignalRChartApp** project and select **Manage NuGet Packages**. ![Select Manage NuGet Packages](https://www.syncfusion.com/blogs/wp-content/uploads/2023/02/Manage-NuGet-Packages.png)
2. Now, confirm that the **Package source** is set to **nuget.org**. ![Set the Package source to nuget.org](https://www.syncfusion.com/blogs/wp-content/uploads/2023/02/Package-source-is-set-to-nuget.org_-1.png)
3. Search for and select the **Microsoft.AspNetCore.SignalR.Client** package and then install it. ![Select Microsoft.AspNetCore.SignalR.Client package](https://www.syncfusion.com/blogs/wp-content/uploads/2023/02/Microsoft.AspNetCore.SignalR.Client-package.png)

### Step 2: Add SignalR hub to the project.

Let’s add the SignalR hub to the Blazor server-side project:

1. In the **Solution Explorer** window, right-click the **BlazorSignalRChartApp** project and add a folder called **Hubs**. Then, add a class called **ChartHub**. The class should inherit from the SignalR’s **Hub** class, which is in the **Microsoft.AspNetCore.SignalR** namespace. Refer to the following code example.
```csharp
using Microsoft.AspNetCore.SignalR;
namespace BlazorSignalRChartApp.Server.Hubs
{
    public class ChartHub : Hub
    {
        
    }
}
```
2.Finally, to complete the configuration for the SignalR, add the endpoint for the hub in the **Program.**** cs** file like in the following code example.
```csharp
using BlazorSignalRChartApp.Server.Hubs;
builder.Services.AddSignalR();
app.MapHub<ChartHub>("/charthub");
app.MapFallbackToPage("/_Host");
```

This code adds the SignalR to the request pipeline by pointing to the **ChartHub** class with the provided **/charthub** path.

## Step 3: Add Syncfusion Blazor Charts to the project.

Next, we are going to use the [Syncfusion Blazor Charts](https://www.syncfusion.com/blazor-components/blazor-charts "Syncfusion Blazor Charts Component") component to create a real-time chart. First, install the charts package:

1. In the **Solution Explorer** window, right-click the **BlazorSignalRChartApp** project and select **Manage NuGet Packages**.
2. Then, confirm that the  **Package source** is set to **nuget.org**.
3. Search for and select the **Syncfusion.**** Blazor.Chart package** and then install it.
4. Open the **~/\_Imports.razor** file and import the **Syncfusion.Blazor** namespace in it.
```csharp
@using Syncfusion.Blazor
```
5.Then, open the **~/Program.cs** file and register the Syncfusion Blazor Service.
```csharp
using BlazorSignalRChartApp.Server.Hubs;
using Syncfusion.Blazor;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddSignalR();
builder.Services.AddSyncfusionBlazor();
```

  a. Open the **\_Layout.cshtml** file and add the following script reference in it.
```xml
<script src="https://cdn.syncfusion.com/blazor/syncfusion-blazor-base.min.js"></script>
<script src="https://cdn.syncfusion.com/blazor/20.3.47/syncfusion-blazor.min.js"></script>
```
  b. Add the Syncfusion Blazor Charts component in the Razor file. The Charts component is added in the **~/Pages/Index.razor** file under the **~/Pages** folder.
```xml
@using Syncfusion.Blazor.Charts
<SfChart>
</SfChart>
```
  c. Press **Ctrl+F5** (Windows) or ⌘+F5 (macOS) to run the application. Then, the Syncfusion Blazor Charts component will be rendered in the default web browser.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/02/Adding-Syncfusion-Blazor-Charts-Component-in-the-Server-Side-App.png" alt="Adding Syncfusion Blazor Charts Component in the Server-Side App" style="width:100%">

  <figcaption>Adding Syncfusion Blazor Charts Component in the Server-Side App</figcaption>

<figure>

## Step 4: Updating data to the chart through SignalR.

We have configured the SignalR server and added the Syncfusion Blazor Charts control in the client. Next, let’s see how to populate data to the chart through SignalR client:

1. First, create a class named **ChartData** with **Date** and **Value** as properties inside the **Data** folder.
```csharp
public class ChartData
{
    Public DateTime Date { get; set; }
    public int Value { get; set; }
}
```
2.Inside the **ChartHub** class, add the **UpdateData()** hub method to send the list of ChartData to the client when called. Refer to the following code.
```csharp
public async Task UpdateData()
{
   await Clients.All.SendAsync("ReceiveMessage", GetData());
}

public static List<ChartData> GetData()
{
   var r = new Random();
   return new List<ChartData>()
   {
      new ChartData { Date = new DateTime(2022, 2, 2), Value = r.Next(1, 40) },
      new ChartData { Date = new DateTime(2022, 3, 2), Value = r.Next(1, 40) },
      new ChartData { Date = new DateTime(2022, 4, 2), Value = r.Next(1, 40) },
      new ChartData { Date = new DateTime(2022, 5, 2), Value = r.Next(1, 40) }
   };
}
```
3.Next, create a connection to the hub ( **charthub** ) with the following code in the **OnInitializedAsync** method of the **Index.razor** file. Then, start the connection with the **StartAsync** method.
```csharp
private HubConnection? hubConnection;
protected override async Task OnInitializedAsync()
{
   hubConnection = new HubConnectionBuilder()
      .WithUrl(NavigationManager.ToAbsoluteUri("/charthub"))
      .Build();     
        await hubConnection.StartAsync();
}
```
4.The connection is established. Let’s replace the empty chart in the **Index.razor** file with a line chart. Refer to the following code example.
```xml
<SfChart Title="Stock Price Analysis of Product X">
  <ChartArea><ChartAreaBorder Width="0"></ChartAreaBorder></ChartArea>
    <ChartPrimaryXAxis ValueType="Syncfusion.Blazor.Charts.ValueType.DateTime">
       <ChartAxisMajorGridLines Width="0"></ChartAxisMajorGridLines>
    </ChartPrimaryXAxis>
    <ChartPrimaryYAxis Title="Price" Minimum="0" Maximum="40" Interval="4" LabelFormat="${value}">
      <ChartAxisLineStyle Width="0"></ChartAxisLineStyle>
      <ChartAxisMajorTickLines Width="0"></ChartAxisMajorTickLines>
    </ChartPrimaryYAxis>
    <ChartTooltipSettings Enable="true"></ChartTooltipSettings>
    <ChartSeriesCollection>
       <ChartSeries Type="ChartSeriesType.Line">
       </ChartSeries>
    </ChartSeriesCollection>
</SfChart>
```
5.Then, call the **hub** method on the server with the specified method name using **SendAsync**.
```csharp
await hubConnection.SendAsync("UpdateData");
```
6.Then, assign the data received by the client to the chart and map the **XName** and **YName** properties of the chart series.
```xml
<ChartSeriesCollection>
  <ChartSeries DataSource="@Data" XName="Date" Width="2"
                  YName="Value" Type="ChartSeriesType.Line">
  </ChartSeries>
</ChartSeriesCollection> 

@code {
 public List<ChartData> Data;
 hubConnection.On<List<ChartData>>("ReceiveMessage", (data) =>
 {
      Data = data;           
      InvokeAsync(StateHasChanged);          
 });
}
```
7.Press **Ctrl+F5** (Windows) or  **⌘+F5** (macOS) to run the application. Then, the Syncfusion Blazor Charts component with data from SignalR will be rendered in the default web browser.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/02/Updating-Real-Time-Chart-Data-Using-SignalR-in-Blazor-Server-Side-App.png" alt="Updating Real-Time Chart Data Using SignalR in Blazor Server-Side App" style="width:100%">

  <figcaption>Updating Real-Time Chart Data Using SignalR in Blazor Server-Side App</figcaption>

<figure>

8.Let’s create a timer that runs the **AddData** method to update the data in the chart through SignalR every two seconds. Now, every two seconds, the data from SignalR will be fed to the chart. Refer to the following GIF image.
<figure>

  <img src="https://www.syncfusion.com/blogs/wp-content/uploads/2023/02/Updating-Real-Time-Chart-Data-Every-Two-Seconds-Using-SignalR-in-Blazor-Server-App.gif" alt="Updating Real-Time Chart Data Every Two Seconds Using SignalR in Blazor Server App" style="width:100%">

  <figcaption>Updating Real-Time Chart Data Every Two Seconds Using SignalR in Blazor Server App</figcaption>

<figure>

## GitHub reference

For the complete example, check out the [creating a real-time chart using SignalR in a Blazor server-side app demo on GitHub](https://github.com/SyncfusionExamples/BlazorSignalRChartApp "Creating a real-time chart using SignalR in a Blazor server-side app GitHub demo").

## Conclusion

Thanks for reading! In this blog, we’ve seen how to create and update a real-time chart in a Blazor server-side app using the Syncfusion [Blazor Charts component](https://www.syncfusion.com/blazor-components/blazor-charts "Syncfusion Blazor Charts Component") and SignalR communication. Try out the steps in this blog and leave your valuable feedback in the comments section.

Essential Studio for [Blazor](https://www.syncfusion.com/blazor-components "Syncfusion Blazor UI components library") offers over 80+ UI components and file-format libraries. Use them to build world-class applications!

For questions, you can contact us through our [support forums](https://www.syncfusion.com/forums "Syncfusion Support Forum"), [support portal](https://support.syncfusion.com/ "Syncfusion Support Portal"), or [feedback portal](https://www.syncfusion.com/feedback/ "Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [Get Real-Time Updates in Blazor WebAssembly Apps with SignalR Communication](https://www.syncfusion.com/blogs/post/get-real-time-updates-in-blazor-wasm-apps-with-signalr-communication.aspx "Blog: Get Real-Time Updates in Blazor WebAssembly Apps with SignalR Communication")
- [Boosting Performance of Blazor Gantt Chart Using Virtualization](https://www.syncfusion.com/blogs/post/boosting-performance-of-blazor-gantt-chart-using-virtualization.aspx "Blog: Boosting Performance of Blazor Gantt Chart Using Virtualization")
- [Easily Use a Dynamic Blob Container in the Blazor File Manager](https://www.syncfusion.com/blogs/post/easily-use-a-dynamic-blob-container-in-the-blazor-file-manager.aspx "Blog: Easily Use a Dynamic Blob Container in the Blazor File Manager")
- [A Full-Stack Web App Using Blazor WebAssembly and GraphQL—Part 7](https://www.syncfusion.com/blogs/post/a-full-stack-web-app-using-blazor-webassembly-and-graphql-part-7.aspx "Blog: A Full-Stack Web App Using Blazor WebAssembly and GraphQL—Part 7")