With my recent project that I built with react, I noticed a gap. My data is on the fly, it cannot be saved. For this, the idea that came back to my head, to look for an API that serves as a backup.
In this article, I will try to go through some important points of how to set up and build a Rails API with react as front-end to help even those who did not even know it
As I plan to work with the Rails API for the backend and React for the frontend, I would like to catalog a bit of what I'm going to do and highlight the right path for others to follow the same route.
When I tried writing the steps on how to create the backend and frontend repositories locally and plug them into GitHub, I started to mix them up. So, to keep track of the steps and for anyone else who needs a refresher, I leave this step-by-step guide here!
As a prerequisite, before creating your Rails API, I recommend that you configure your database with Postgres because it is easier to deploy than SQLite. After that locate on your directory and create a new project by typing this command:
rails new <app_name> --api --database=postgresql
cd
<app_name>
the --database flag is for choosing our DB engine, we're using Postgresql, and --api is to create a rails-based API to use just the things we'll need to and skip extra configuration we won't use.
Open the project using your favorite editor. Then open Gemfile and add rack-cors:
gem 'rack-cors', :require => 'rack/cors'
Then, run bundle install
Before you run your new Rails application, you have to first connect it to a database. In this step, you’ll connect the newly created Rails application to a PostgreSQL database, so recipe data can be stored and fetched when needed. you have to type:
rails db:create
Your output will be something like this:
Created database 'app_name_development'
Created database 'app_name_test'
Open your Terminal and run the following commands to create controllers and models:
rails generate model Movie name rating:integer
rails generate controller Movies index create update destroy
rails db:migrate
When you open the controller you created you will see the controller generated with empty methods
Let’s implement those methods to get our API functional
Now that we have a controller that manages our model, we will copy some movies to the seed.rb
file, to display them in our browser, to test if we can get the data into the json format.
copy these movies below:
Movie.create(name: "Titanic", rating: 5)
Movie.create(name: "We were soldiers", rating: 4)
Movie.create(name: "L’amour quand elle nous tient", rating: 5)
Movie.create(name: "Nobody's Fool", rating: 2)
After, paste those four elements into your projects run rails db:seed
We are now ready to do some coding! Let's start with route.rb. If you open the file, you will find routes automatically generated with the controllers. As we will be defining our own routes for the APIs, we are going to remove them to define the new routes / APIs:
Rails.application.routes.draw do
resources :movies
end
To see your application, open a browser window and navigate to http://localhost:3000. You will see the Rails default welcome page. but when you add the routes, it means http://localhost:3000/movies, you will get all the movies we seed in our database.
You can install any JSON viewer extension on your browser to see formatted data.
Great, our rails Api work perfectly. now let’s start with the frontend.
Now that we have a basic API, let’s set up our front-end React app using
npx create_react-app.
Create React App is a project by Facebook that helps you get started with a React app quickly without any configuration.
First, make sure you have Node.js and npm installed. You can download the installer from the Node.js website. Then install Create React App by running:
And then, make sure you're outside of the Rails directory, and run the following command to create react app:
npx create-react-app my_react
This will create a react app that will communicate with our api. enter inside the directory by typing cd my_react
and run npm start.
This will open it on http://localhost:3000.
One of the main advantages of React is the concept of Components. According to React website:
Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
We are going to delete all unnecessaries
files like this picture and create our
own components.
In the source directory, we are going to create a new folder components where we put our files that we are going to display.
Let’s create our first component. Let’s create a new file in todo-app/src/components/Movie.js:
import React, { Component } from 'react';
class Song extends Component {
render() {
return (
<div>
<h1>movies</h1>
</div>
);
}
}
export default Song;
Okay that’s our component. let’s import it in our app file for to display it to our browser.
import './App.css';
import Song from './components/Song';
function App() {
return (
<div className="App">
<Song />
</div>
);
}
export default App;
It’s time to load the data from the backend. You can use any package to fetch/store data. I use axios.
Install axios and import it in the Movie component.
npm install axios --save
Let’s start by initializing the state in the constructor with ideas as an empty array:
constructor(props) {
super(props)
this.state = {
movies: []
}
}
As we already initialized the state in our components, let’s now implement the componentDidMount() method to load our datas from the API:
componentDidMount() {
axios.get('http://localhost:3000/movies')
.then(response => {
console.log(response)
this.setState({movies: response.data})
})
.catch(error => console.log(error))
}
import axios from 'axios'
remember to import axios: import axios from 'axios'
Up to this point, you cannot get your data, you will be blocked by cors.
To avoid this you have to go in API, inter in config/aplication.rb and insert:
config.middleware.insert_before 0, Rack::Cors do
allow do
origins 'http://localhost:3000' resource '*', :headers => :any, :methods => [:get, :post, :put, :delete, :options]
end
end
Great, now you can access to your datas, in the console.
So now that we know we’re able to fetch ideas from our API, let’s use them in our React component. We can change the render function to iterate through the list ideas from the state and display each of them:
render() {
return (
<div>
{this.state.movies.map((movie) => {
return(
<div className="tile" key={movie.id} >
<h2>{movie.name}:<span>{movie.rating}</span></h2>
</div>
)
})}
</div>
);
}
Perfect, now we can see our data in the browser. thank you.
If you have followed all the steps, I hope you have something like this in your browser:
If you with to learn how you implement react inside rails, follow this tutorial.
For other links, take look at: https://guides.rubyonrails.org/api_app.html