locked
How to display new data from REST API with SignalR? RRS feed

  • Question

  • User-1634202039 posted

    So I have REST APIs that return new data every couple minutes. How to display the new data without making the user to the refresh the browser every time?

    This is what I have so far.

    AppController.cs

    public IActionResult Index()
    {
        string[] day = {"Mon", "Tue", "Wed", "Thu", "Fri"};
        List<API> results = new List<API>();
        for (var i = 0; i < day.Length; i++)
        {
            var client = new RestClient("https://api.example.com/values/d=" + day[i]);
            var request = new RestRequest(Method.GET);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("accept", "application/json; charset=utf-8");
            IRestResponse response = client.Execute(request);
            var responseContent = response.Content;
    
            results.Add(new JavaScriptSerializer().Deserialize<API>(responseContent));
        }
    
        return View(results);
    }

    APIHub.cs

    using Microsoft.AspNetCore.SignalR;
    using System.Threading.Tasks;
    
    namespace SignalRAPI.Hubs
    {
        public class APIHub : Hub
        {
            public async Task SendData(   )
            {
                await Clients.All.SendAsync(    );
            }
        }
    }

    index.cshtml

    @model Site.Models.API
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Live data</title>
    </head>
    
    <body>
    <div><h3>Data: <h3></div>
    <div class="APIDataResult" id="APIDataResult>@Html.DisplayFor(modelItem => model.APIdata)</div>
    <script>
            var connection = new signalR.HubConnectionBuilder()
                                        .withUrl('/APIHub')
                                        .build();
            connection.on({        });
            connection.start(   )
    </script>
    </body>
    </html>

    Wednesday, November 6, 2019 6:22 PM

All replies

  • User475983607 posted

    You can use SingnlR but your approach is not correct.  The SignalR client and server interact through the hub not an action.  The SignalR doc go into great details and you can certainly take the time to go through the docs.

    A very simple approach is meta tag refresh.

    https://www.w3schools.com/tags/att_meta_http_equiv.asp

    Another us using a JavaScript timer to invoke an AJAX or fetch function that calls the Index method.  Just Google, there are tons of examples in the internet but you'll write code to update the DOM if you go this route.

    Wednesday, November 6, 2019 8:59 PM
  • User-1634202039 posted

    Will the following code is how it should be?

    <script>
      function fetchdata() {
          $.ajax({
            type: 'GET',
            url: '@Url.Action("index")',
            success: function (result) {
              $('#APIDataResult').html(result);
            }
          });
        });
      });
    
    $(document).ready(function(){
     setInterval(fetchdata,5000);
    });
    
    </script>



    Wednesday, November 6, 2019 9:58 PM
  • User475983607 posted

    Looks correct, but you'll want to return a partial view.  A partial view does not have include the layout view.

    Wednesday, November 6, 2019 10:22 PM
  • User61956409 posted

    Hi iadn,

    I have REST APIs that return new data every couple minutes. How to display the new data without making the user to the refresh the browser every time?

    If you'd like to automatically display new data from REST API in your view page without reloading/refreshing the page, as mgebhard mentioned, you can use JavaScript timer to retrieve data by consuming the API at every given time-interval, then populate new data on your web page.

    Besides, if you'd like to achieve the requirement by using SignalR, you can create and use a scheduled job/background task to consume the API and retrieve the new data,  then you can connect to the SignalR hub server and invoke SignalR hub method to push new data to all connected clients from scheduled job/background task, and then repopulate new data on your page using JavaScript.

    With Regards,

    Fei Han

    Thursday, November 7, 2019 1:45 AM
  • User-1634202039 posted

    Hello Fei Han,

    What do you mean by "retrieve data by consuming the API at every given time-interval"?

    Thursday, November 7, 2019 7:58 PM
  • User-1634202039 posted

    Looks correct, but you'll want to return a partial view.  A partial view does not have include the layout view.

    The Index method will return a list based on API model. The JavaScript timer will invoke fetch function that calls the Index method. My question is, will this also execute API GET Request every time? 

    Thursday, November 7, 2019 8:08 PM
  • User475983607 posted

    The Index method will return a list based on API model. The JavaScript timer will invoke fetch function that calls the Index method. My question is, will this also execute API GET Request every time? 

    The JavaScript timer shown above executes the fetchdata() function every 5 seconds.   Are you having a problem or unexpected results?  Can you clarify?

    Thursday, November 7, 2019 8:49 PM
  • User-1634202039 posted

    The JavaScript timer shown above executes the fetchdata() function every 5 seconds.   Are you having a problem or unexpected results?  Can you clarify?

    The ajax call above returns the Index View. But I want to return the API list (inside the controller) so I can loop through it and display it.

    Thursday, November 7, 2019 11:20 PM
  • User61956409 posted

    Hi iadn,

    The ajax call above returns the Index View. But I want to return the API list (inside the controller) so I can loop through it and display it.

    Why not make ajax request to your API endpoint directly, then repopulate the page content based on retrieved data using JavaScript/jQuery.

    With Regards,

    Fei Han

    Friday, November 8, 2019 3:22 AM