Skip to content

Latest commit

 

History

29 Commits

Folders and files

Repository files navigation

Step 1: Set Up the React.js Project

  1. Create a New React App: Open your terminal and run the following command to create a new React application:

    npx create-react-app library-management-system
    cd library-management-system
  2. Install Axios: Axios will be used to make HTTP requests to the Flask backend.

    npm install axios
  3. Project Structure: Organize your project structure. You can create folders for components, services, and styles:

    library-management-system/
    ├── src/
    │   ├── components/
    │   ├── services/
    │   ├── App.js
    │   ├── index.js
    │   └── ...
    

Step 2: Set Up the Flask Backend

  1. Create a New Flask Project: Create a new directory for your Flask backend and set up a virtual environment:

    mkdir flask-backend
    cd flask-backend
    python -m venv venv
    source venv/bin/activate  # On Windows use `venv\Scripts\activate`
  2. Install Flask and Flask-CORS: Install Flask and Flask-CORS to handle cross-origin requests:

    pip install Flask Flask-CORS
  3. Create the Flask Application: Create a file named app.py in the flask-backend directory:

    from flask import Flask, jsonify, request
    from flask_cors import CORS
    
    app = Flask(__name__)
    CORS(app)
    
    # Sample data (replace with database connection later)
    authors = [
        {"author_id": 1, "firstname": "Frank", "lastname": "Herbert"},
        {"author_id": 2, "firstname": "J.R.R.", "lastname": "Tolkien"},
    ]
    
    @app.route('/api/authors', methods=['GET'])
    def get_authors():
        return jsonify(authors)
    
    @app.route('/api/authors', methods=['POST'])
    def add_author():
        new_author = request.json
        new_author['author_id'] = len(authors) + 1
        authors.append(new_author)
        return jsonify(new_author), 201
    
    if __name__ == '__main__':
        app.run(debug=True)
  4. Run the Flask Application: In the terminal, run the Flask app:

    python app.py

Step 3: Connect React to Flask

  1. Create a Service to Handle API Calls: In the src/services directory, create a file named api.js:

    import axios from 'axios';
    
    const API_URL = 'http://localhost:5000/api';
    
    export const getAuthors = async () => {
        const response = await axios.get(`${API_URL}/authors`);
        return response.data;
    };
    
    export const addAuthor = async (author) => {
        const response = await axios.post(`${API_URL}/authors`, author);
        return response.data;
    };
  2. Update the App Component: Modify src/App.js to fetch authors from the Flask backend:

    import React, { useEffect, useState } from 'react';
    import { getAuthors, addAuthor } from './services/api';
    
    const App = () => {
        const [authors, setAuthors] = useState([]);
        const [newAuthor, setNewAuthor] = useState({ firstname: '', lastname: '' });
    
        useEffect(() => {
            const fetchAuthors = async () => {
                const authorsData = await getAuthors();
                setAuthors(authorsData);
            };
            fetchAuthors();
        }, []);
    
        const handleAddAuthor = async () => {
            const addedAuthor = await addAuthor(newAuthor);
            setAuthors([...authors, addedAuthor]);
            setNewAuthor({ firstname: '', lastname: '' });
        };
    
        return (
            <div>
                <h1>Library Management System</h1>
                <h2>Authors</h2>
                <ul>
                    {authors.map(author => (
                        <li key={author.author_id}>{author.firstname} {author.lastname}</li>
                    ))}
                </ul>
                <input
                    type="text"
                    placeholder="First Name"
                    value={newAuthor.firstname}
                    onChange={(e) => setNewAuthor({ ...newAuthor, firstname: e.target.value })}
                />
                <input
                    type="text"
                    placeholder="Last Name"
                    value={newAuthor.lastname}
                    onChange={(e) => setNewAuthor({ ...newAuthor, lastname: e.target.value })}
                />
                <button onClick={handleAddAuthor}>Add Author</button>
            </div>
        );
    };
    
    export default App;

Step 4: Run the React Application

  1. Start the React App: In a new terminal window, navigate to the React project directory and run:

    npm start

Step 5: Test the Application

  1. Open your browser and navigate to http://localhost:3000. You should see the Library Management System interface where you can view and add authors.

Step 6: Connect to a Database (Optional)

To connect your Flask application to a database (like SQLite, PostgreSQL, etc.), you can use an ORM like SQLAlchemy. Here’s a brief overview of how to do that:

  1. Install SQLAlchemy:

    pip install SQLAlchemy
  2. Set Up the Database: Modify your Flask app to include database models and queries instead of using hardcoded data.

  3. Update API Endpoints: Change the API endpoints to interact with the database instead of the hardcoded list.

This setup provides a basic structure for a Library Management System using React and Flask. You can expand upon this by adding more features, such as managing books, publishers, and loans, as well as implementing user authentication.

About

Library management System

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages