why doesn't my datatable change immediately? must be refreshed first. I've been looking for it but haven't found the right solution yet. when running, a message appears on the console, the connection is successful, then the connection is lost. like I'm confused how to implement the correct one. please help me
hub
public class TransactionHub: Hub
{
}
Repository
private readonly IHubContext<TransactionHub> _context;
private readonly IConfiguration _configuration;
private readonly string BASE_URL;
public TransactionRepository(IConfiguration configuration, IHubContext<TransactionHub> context)
{
_configuration = configuration;
BASE_URL = _configuration["BaseUrl"];
_context = context;
}
public async Task<List<Transaction>> GetAllTransaction(string token)
{
var transaction = new List<Transaction>();
var apiUrl = BASE_URL + "/Transaction";
var response = await RequestGet(ClientBase(token), apiUrl);
var result = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
var jsonDeserializeSettings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Objects
};
var apiResponse = JsonConvert.DeserializeObject<ApiResponse<List<Transaction>>>(result, jsonDeserializeSettings);
transaction = apiResponse.data;
}
await _context.Clients.All.SendAsync("refreshTransactions");
return transaction;
}
Controller
public async Task<IActionResult> GetAllTransaction()
{
List<Transaction> transactions = await _transactionRepository.GetAllTransaction("token");
var jsonData = Json(new
{
data = transactions
});
return jsonData;
}
javascript
$(() => {
let connection = new signalR.HubConnectionBuilder().withUrl("/transactionhub").build()
connection.start()
connection.on("refreshTransactions", function () {
loadData()
})
loadData();
function loadData() {
let table = $('#transactionList').DataTable({
"pagingType": "simple",
"autoWidth": true,
"ajax": {
"url": "/GetAllTransaction",
"type": "GET",
"datatype": "json",
},
"columns": [
{ "data": "email", "autoWidth": true, "searchable": true },
{ "data": "stationName", "autoWidth": true, "searchable": true },
],
});
})
startup
services.AddSignalR();
endpoints.MapHub<TransactionHub>("/transactionhub");