TODO from React + Rails Part 8: Realtime with Action Cable

Tram Ho

In the previous articles, I have finished the TODO App with the most basic functions such as Add, Update, Delete, Done, … Today I will implement more realtime functions for those operations. As you know from Rails 5 and above, there is action cable support available to do realtime for your Rails project.

Implement server side

First, generate channel:

It will create the following files:

In the app/channels/tasks_channel.rb

Here, I will be subscribed to the channel named tasks_channel. Data broadcast to this channel will receive it.

Next in the controller I will broadcast to the tasks_channel channel with the necessary data as follows:

Each action has a type used for the client to know from which actions the data received is.

Implement side

Actioncable not only supports server side, it also supports Reactjs.

On the Client side, we will need 3 main steps as follows:

  • Connecting to ‘/ cable’
  • Subscribe to the ‘tasks_channel’ channel
  • Listen to receive data

In the src / TodoList.js file, in componentDidMount modify the code as follows:

Come here is done. =))

Result:

To understand actioncable details, go to its document.

https://guides.rubyonrails.org/action_cable_overview.html

Share the news now

Source : Viblo