How to update a database according to SignalR?

Viewed 329

First of all, I work according to this guide: Creating a simple real-time chat with .NET Core, ReactJS and SignalR https://medium.com/swlh/creating-a-simple-real-time-chat-with-net-core-reactjs-and-signalr-6367dcadd2c6

(Tip: Highly recommended guide. Easy and understandable)

I did this guide, it works great.

And now for real life ...

I have a blog. My blog currently has a database that I call with axios and it is stored in a database. But it is not updated when there is a change in the database.

I want to upgrade the site and receive an alert message every time there is an update in the system (new post, new comment, new like, etc.)

I did not quite understand how to combine this.

I thought (according to the division of the above guide) in the chat.js component

connection
      .start ()
      .then ((result) => {
        connection.on ("ReceiveMessage", (message) => {
          const updatedChat = [... latestChat.current];
          updatedChat.push (message);
          ** setNew (true); <-------- **
          setChat (updatedChat);
        });
      })

Set him to get new data to change state to true and then it will access a database to get new information through the axios.

I think it's cumbersome, is there a way to define it directly?

1 Answers

I have a blog. My blog currently has a database that I call with axios and it is stored in a database. But it is not updated when there is a change in the database.

I want to upgrade the site and receive an alert message every time there is an update in the system (new post, new comment, new like, etc.)

In you blog system, it seems that user could do with or update blog/comment by making HTTP request to backend service using axios.

If you'd like to push some real-time notifications/data to connected SignalR client(s) while someone make changes to blog or comment, you can try to inject an instance of IHubContext in your API controller, then send message to SignalR clients from your controller action after you update database.

For more information about "Send messages from outside a hub", please check:

https://docs.microsoft.com/en-us/aspnet/core/signalr/hubcontext?view=aspnetcore-5.0

Related