skip to Main Content

I am trying to fetch data from the database and present them on the front-end page of a web application.
When I click different fridge buttons, it always shows "No items found in this fridge." on my page.
For the front end, I use JavaScript and React.js. The back-end is done by Python + Flask.
Can anyone help me find the reason and correct it?

front end page1
front end page2

SpecificFridge.js:

import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import NavBar from '../components/NavBar';
import './Style.css';

const SpecificFridge = () => {
    const { fridgeNumber } = useParams();
    console.log("fridgeNumber:", fridgeNumber); 
    const [items, setItems] = useState([]);

    useEffect(() => {
        fetch(`/api/fridge/${fridgeNumber}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => setItems(data))
            .catch(error => console.error('Error fetching fridge data:', error));
    }, [fridgeNumber]);

    return (
        <div className="specific-fridge-page">
            <NavBar/>
            <div className='specific-fridge-content'>
                <h1>Fridge {fridgeNumber}</h1>
                <table>
                    <thead>
                        <tr>
                            <th>Item Name</th>
                            <th>Entry Date</th>
                            <th>Expiry Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        {items.length === 0 ? (
                            <tr>
                                <td colSpan="3">No items found in this fridge.</td>
                            </tr>
                        ) : (
                            items.map((item, index) => (
                                <tr key={index}>
                                    <td>{item.itemName}</td>
                                    <td>{item.entryDate}</td>
                                    <td>{item.expiryDate}</td>
                                </tr>
                            ))
                        )}
                    </tbody>
                </table>
            </div>
        </div>
    );
};

export default SpecificFridge;

Fridge.js:

import React, { useState } from 'react';
import NavBar from '../components/NavBar';
import FridgeButton from '../components/FridgeButton';
import SpecificFridge from '../pages/SpecificFridge';
import './Style.css';

const Fridges = () => {
    const [selectedFridge, setSelectedFridge] = useState(null);
    const handleFridgeClick = (fridgeNumber) => {
        setSelectedFridge(fridgeNumber);
    };

    return (
        <div className="fridges-page">
            <NavBar />
            <div className="fridges-content">
                <h1>Total overview of all fridges</h1>
                <div className="fridges-container">
                    <FridgeButton fridgeNumber={1} onClick={() => handleFridgeClick(1)} />
                    <FridgeButton fridgeNumber={2} onClick={() => handleFridgeClick(2)} />
                    <FridgeButton fridgeNumber={3} onClick={() => handleFridgeClick(3)} />
                    <FridgeButton fridgeNumber={4} onClick={() => handleFridgeClick(4)} />
                </div>
                {selectedFridge !== null && <SpecificFridge fridgeNumber={selectedFridge} />}
            </div>
        </div>
    );
};

export default Fridges;

app.py

from flask import Flask, jsonify, request
import sqlite3


app = Flask(__name__)


def get_db_connection():
    conn = sqlite3.connect('stock.db')
    conn.row_factory = sqlite3.Row
    return conn


@app.route('/api/fridge/<int:fridgeNumber>', methods=['GET'])
def get_fridge_items(fridgeNumber):
    conn = None
    try:
        conn = get_db_connection()
        items = conn.execute('SELECT itemName, entryDate, expiryDate FROM STOCK WHERE fridgeNumber = :fridgeNumber', {'fridgeNumber': fridgeNumber}).fetchall()
        items_list = [dict(item) for item in items]
        return jsonify(items_list)
    except Exception as e:
        print(f"An error occurred: {e}")
        return jsonify({"error": "An error occurred while fetching data"}), 500
    finally:
        if conn:
            conn.close()


if __name__ == '__main__':
    app.run(debug=True)

The fridgeNumber can be printed out at console.

2

Answers


  1. I think it’s because in the API call, you pass the fridgeNumber as String and the server side type is an integer so can you just log the type of fridgeNumber in console.
    and just pass as props ({fridgeNumber}) not use useParams()

    Login or Signup to reply.
  2. It is because your "specific fridge" has never received the fridge number. In you code you read the fridge number from router params. But you are passing it as a prop from parent component. You should read it from props and pass to the API

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search