As of now the Rails view is building the list of "Tasks" and the server is responding with the HTML.
Now we will switch to the API style where the server will primarily send data as JSON API and the client will build the HTML. This is different from the "pure API" style that we discussed in the last chapter. Here the frontend code and the backend code are in the same repository.
Deleting Rails views
As we will be sending JSON responses from controllers we don't need this tasks/index.html.erb file. We can remove this file like so:
1rm app/views/tasks/index.html.erb
Sending JSON response from the controllers
Let's open app/controllers/tasks_controller.rb and let's change the index action.
Since tasks in no longer required in its corresponding view file, we can remove the @ sign as it needn't be an instance variable:
1class TasksController < ApplicationController 2 def index 3 tasks = Task.all 4 render status: :ok, json: { tasks: } 5 end 6end
In Ruby 3.1.2, we can omit the values in hash literals and keyword arguments.
For example, { x: , y: } is a syntax sugar of { x: x, y: y }. Similarly foo( x:, y: ) is a syntax sugar of foo( x: x, y: y ).
So, the json response in the above mentioned index action is equivalent to { tasks: tasks }.
For more details please refer to this issue from the Ruby org.
If we open new task page by going to the URL http://localhost:3000/tasks we will be getting the response in the JSON format.
Configuring React for API based architecture
Let's create a new controller called Home:
1bundle exec rails generate controller Home
It will generate the following files:
1Running via Spring preloader in process 8810 2 create app/controllers/home_controller.rb 3 invoke erb 4 create app/views/home 5 invoke test_unit 6 create test/controllers/home_controller_test.rb 7 invoke helper 8 create app/helpers/home_helper.rb 9 invoke test_unit 10 invoke assets 11 invoke scss 12 create app/assets/stylesheets/home.scss
Now let's create an index action:
1class HomeController < ApplicationController 2 def index 3 render 4 end 5end
We have already created our entry point App.jsx, in the chapter for setting up react environment.
App.jsx will act as the single entry point to the React client and react-router will be used for routing in the React side.
We will be serving App.jsx when the home#index action is called.
So now, we need to create a view file for home#index, if it doesn't exist already:
1touch app/views/home/index.html.erb
Add the following line in to app/views/home/index.html.erb:
1<%= react_component 'App' %>
Updating Rails routes
Open config/routes.rb and add following lines:
1Rails.application.routes.draw do 2 resources :tasks, only: :index 3 4 root "home#index" 5 get '*path', to: 'home#index', via: :all 6end
Now visit http://localhost:3000/ and this time we should get message Home.
Now let's commit these changes:
1git add -A 2git commit -m "Added API based architecture"