Building a Bookstore Web Application with Rails API and React
Let’s get started!
Step 1: Setting up the Rails API Backend
First, open your terminal and navigate to the desired directory where you want to create the project. Run the following command to generate a new Rails API application:
rails new bookstore --api
cd bookstore
Next, we need to install the necessary dependencies. Open the `Gemfile` and add the following line:
gem 'rack-cors'
Save the file and run the `bundle install` command to install the gem.
We now need to configure CORS to allow cross-origin requests. Open the `config/application.rb` file and add the following code inside the `Rails.application.configure do` block:
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins "http://localhost:3001"
resource "*",
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
This code allows requests from `http://localhost:3001`, which is the default address for a React development server. Make sure to replace `”http://localhost:3001"` with the appropriate domain or URL of your React application in production.
To test the API configuration, let’s generate a sample resource. Run the following command to create a `Book` resource:
rails g scaffold Book title:string body:text
rails db:migrate
Finally, we need to set up a route for our API. Open the `config/routes.rb` file and add the following code:
namespace :api do
namespace :v1 do
resources :books
end
end
This code creates a namespace for the API version and sets up the `books` resource.
It's great! The Rails API backend is now ready to serve book data.
Step 2: Creating the React Frontend:
Open a new terminal window and navigate to the directory you want to create your React front end. Run the following commands to create a new React app and install the required dependencies:
npx create-react-app bookable
cd bookable
npm install axios
Next, let’s write the code to connect the React app to the Rails API and fetch book data.
Open the `src/App.js` file and replace the existing code with the following:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Books from './components/books';
const API_URL = "http://localhost:3000/api/v1/books";
function App() {
const [books, setBooks] = useState([]);
useEffect(() => {
let mounted = true;
axios.get(API_URL)
.then((response) => {
if (mounted) {
setBooks(response.data);
}
})
.catch((error) => {
console.error(error);
});
return () => {
mounted = false;
};
}, []);
return (
<div className="App">
<h1>Hello</h1>
<
Books books={books} />
</div>
);
}
export default App;
In this code, we use the `axios` library to fetch book data from the Rails API. The `useEffect` hook ensures that the API request is made only once when the component mounts.
Next, let’s create a `Books` component to display the book data. Create a new file named `src/components/books.js` and add the following code:
import React from 'react';
const Books = (props) => {
return (
<div>
<h1>Books from the API</h1>
{props.books.map((book) => (
<div key={book.id}>
<h2>{book.title}</h2>
<p>{book.body}</p>
</div>
))}
</div>
);
};
export default Books;
This component receives the `books` data as a prop and renders a list of book titles and descriptions.
Now, let’s start both the Rails API and React frontend servers. Open one terminal window and run the following command to start the Rails server:
rails s
In another terminal window, navigate to the React app directory (`bookable`) and start the React development server:
npm start
You should now see the “Hello” text and the list of books fetched from the Rails API in your browser.