Transitioning from Static to Dynamic Data in React with Express Backend

20 views Asked by At

I am developing a perfume review application using a React frontend and an Express/SQLite backend. My goal is to transition from using static data within a React component to fetching this data dynamically from my backend.

Project Architecture:

Backend:

  • Models: Parfum.js - Defines the perfume model.

  • Controllers: ParfumController.js - Contains logic to interact with the database.

  • Database Management: database.js - Manages SQLite database operations.

  • API Setup: app.js - Configures Express routes for the API.

Frontend (newfrontend directory):

  • React Component: MainWindow.js - Displays perfume information.

  • Styling: MainWindow.css

Database:

  • SQLite Database: database.db - Stores perfume data.

The backend provides various endpoints, like /api/perfume-name/:id, for fetching perfume names.

Issue:

I need to fetch a list of perfumes from the backend dynamically instead of using static data within MainWindow.js.

Questions:

  1. How can I structure my API call within MainWindow.js to fetch and display perfumes?

  2. Based on the provided database schema and Express routes, how can I update the React component's state with the fetched data?

  3. What are the best practices for error handling in this scenario, especially for failed API calls or when no data is returned?

Attempts:

  • Used axios in MainWindow.js with useEffect to fetch data on component mount.

  • Tested with hardcoded API endpoint URLs, which works fine with static data. Now seeking to implement dynamic data fetching.

Challenges:

  • Encountering CORS errors and issues updating the component's state with fetched data.

  • Unsure how to handle the asynchronous nature of API calls within React effectively

Code Snippets:

database.js:

class Database {
  // Method to initialize database and tables
  _initializeDatabase() {
    // SQL table creation scripts
  }
   
  _Add_Perfume(Perfume) {
    // Add attributes of a Perfume object which contains scraped data in a Perfume Object created in the Model and coming from the controller
  }

  // Example getter
  getPerfumeName(perfumeId) {
    // Implementation
  }

  // Additional getters and setters...
}

app.js backend setup:

import express from 'express';
import cors from 'cors';
import { Database } from './database.js';

const app = express();
app.use(cors());
const port = 3001;

app.get('/api/perfume-name/:id', (req, res) => {
    // Endpoint implementation
});

// More routes...

Desired Outcome:

I'm looking for guidance on fetching data from my Express backend into the MainWindow.js React component to replace the static data setup. Specifically, how to dynamically render this data in the component.

Current Static Setup in React (MainWindow.js):

Below is a snippet from my MainWindow.js component, showing how perfume data is currently hardcoded within the component's state. I aim to replace this static data setup with dynamic data fetched from my backend.

import React, { useState } from 'react';
import './MainWindow.css';

const MainWindow = () => {
  const [perfumes, setPerfumes] = useState([
    {
      id: 1,
      name: 'Sauvage',
      brand: 'Dior',
      imageUrl: 'https://example.com/sauvage.jpg',
      genre: 'Men',
      // Additional perfume details...
    },
    {
      id: 2,
      name: 'Chanel No 5',
      brand: 'Chanel',
      imageUrl: 'https://example.com/chanel-no-5.jpg',
      genre: 'Women',
      // Additional perfume details...
    },
    // Additional perfumes...
  ]);

  // Component rendering logic...
  return (
    <div className="perfume-container">
      {perfumes.map(perfume => (
        <div key={perfume.id} className="perfume-card">
          <img src={perfume.imageUrl} alt={perfume.name} />
          <h2>{perfume.name}</h2>
          <p>Brand: {perfume.brand}</p>
          {/* More perfume details */}
        </div>
      ))}
    </div>
  );
};

export default MainWindow;
0

There are 0 answers