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
We need to create a view file for
home#index, if it doesn't exist already.
Sending JSON response from the controllers
app/controllers/tasks_controller.rb and let's change the
tasks in no longer required in its corresponding view file, we can
@ sign as it needn't be an instance variable:
1class TasksController < ApplicationController 2 def index 5 end 6end
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
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
1class HomeController < ApplicationController 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
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
Add the following line in to
1<%= react_component 'App' %>
Updating Rails routes
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
Now let's commit these changes:
1git add -A 2git commit -m "Added API based architecture"