skip to Main Content

I am a beginner. I am developing a website on React and Using an API for fetching the data but I am not able to display it on the table view. Although I am able to log the data into the console.

Here is the code:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import "./Hero.css"
import Search from '../../Pages/Search/Search';
import { NavLink } from "react-router-dom";
import { useNavigate } from 'react-router-dom';

const Hero = () => {
    const [item, setItem] = useState('');
    const [unit, setUnit] = useState('');
    const [amazon, setAmazon] = useState(false);
    const [costco, setCostco] = useState(false);
    const [walmart, setWalmart] = useState(false);
    const [dollartree, setDollartree] = useState(false);
    const [data, setData] = useState([]);

    const history = useNavigate();

    const handleInputChange = (event) => {
        setItem(event.target.value);
    };

    const handleUnitChange = (event) => {
        setUnit(event.target.value);
    };

    const handleAmazonChange = (event) => {
        setAmazon(event.target.checked);
    };

    const handleCostcoChange = (event) => {
        setCostco(event.target.checked);
    };

    const handleWalmartChange = (event) => {
        setWalmart(event.target.checked);
    };

    const handleDollartreeChange = (event) => {
        setDollartree(event.target.checked);
    };

    const constructAPIUrl = () => {
    const baseUrl = 'http://74.208.39.34/search';
    const queryParams = [`item=${item}`, `unit=${unit}`];

    // Add vendor query params based on checkbox values
    if (amazon) {
        queryParams.push('amazon=y');
    }

    if (costco) {
        queryParams.push('costco=y');
    }

    if (walmart) {
        queryParams.push('walmart=y');
    }

    if (dollartree) {
        queryParams.push('dollartree=y');
    }

    // Add other vendors as needed (e.g., walmart, dollartree)

    return `${baseUrl}?${queryParams.join('&')}`;
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    const apiUrl = constructAPIUrl();

    // Use Axios to make the API request and fetch data in JSON format
        axios
          .get(apiUrl)
          .then((response) => {
            // Handle the fetched data (e.g., update state to display it in the table)
            setData(response.data);
            console.log(response.data);
            history('/search');
            return response;
          })
          .catch((error) => {
            console.error('Error fetching data:', error);
          });
      };


    return(
<div id="page">
    <div className="container">
        <section className="main-section">
            <div className="flex-row">
                <div className="col-2">
                    <div className="banner-ad">
                        <p>Banner Ad</p>
                    </div>
                </div>
                <div className="col-8">
                    <div className="main-form">
                        <h1>BEST PRICE<br/>LARGEST QUANTITY!</h1>
                        <p>Find the cheapest items for sale online by the pound, ounce, gallon, quart, and more!. From Over Multiple venders </p>
                        <div className="my-form">
                            <form onSubmit={handleSubmit}>
                                <div className="inputs">
                                    <input placeholder="Product name" className="prod-input" name="name" id="name" required="" type="text" value={item} onChange={handleInputChange}/>
                                    <select value={unit} onChange={handleUnitChange} className="unit-select" name="desired_units" id="units" required="">
                                        <option selected="" value="">Select Unit</option>
                                        <option value="count">Count</option>
                                        <optgroup label="Weights &amp; Volumes">
                                            <option value="lb">Pounds</option>
                                            <option value="oz">Ounces</option>
                                            <option value="kg">Kilograms</option>
                                            <option value="g">Grams</option>
                                            <option value="mg">Milligrams</option>
                                            <option value="gal">Gallons</option>
                                            <option value="Liter">Liters</option>
                                            <option value="l">Milliliters</option>
                                            <option value="cups">Cups</option>
                                            <option value="qt">Quarts</option>
                                            <option value="pint">Pints</option>
                                        </optgroup>
                                        <optgroup label="Computer Measurements">
                                            <option value="Terabyte">Terabytes (TB)</option>
                                            <option value="Gigabyte">Gigabytes (GB)</option>
                                            <option value="Megabyte">Megabytes (MB)</option>
                                        </optgroup>
                                    </select>
                                </div>
                                <div className="vendor-ticks">
                                <div className="vendor-head"><h2>VENDORS:</h2></div>
                                    <div className="vendor-tick-box">
                                        <div className="vendor-tick"><input type="checkbox" name="options" id="amazon" checked={amazon} onChange={handleAmazonChange}/><label >AMAZON</label></div>
                                        <div className="vendor-tick"><input type="checkbox" name="options" id="walmart" checked={walmart} onChange={handleWalmartChange}/><label >WALMART</label></div>
                                        <div className="vendor-tick"><input type="checkbox" name="options" id="costco" checked={costco} onChange={handleCostcoChange}/><label >COSTCO</label></div>
                                        <div className="vendor-tick"><input type="checkbox" name="options" id="dollartree" checked={dollartree} onChange={handleDollartreeChange}/><label >DOLLARTREE</label></div>
                                    </div>
                                </div>
                                <div className="submit-btn">
                                    {/* <NavLink to="/search" className="submit-button" type="submit">Check</NavLink> */}
                                    <button type="submit">Check</button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
                <div className="col-2">
                    <div className="banner-ad">
                        <p>Banner Ad</p>
                    </div>
                </div>
            </div>
        </section>
        <section className="brands-logo-section">
            <div className="brands-logos">
                <ul>
                    <li><NavLink to="https://www.amazon.com" target="_blank"><img src="./amazon.png" /></NavLink></li>
                    <li><NavLink to="https://www.walmart.com" target="_blank"><img src="./walmart.png" /></NavLink></li>
                    <li><NavLink to="https://www.costco.com" target="_blank"><img src="./costco.png" /></NavLink></li>
                    <li><NavLink to="https://www.dollartree.com " target="_blank"><img src="./dollartree.png" /></NavLink></li>
                </ul>
            </div>
        </section>
    </div>
    <Search data={data} />
</div>
    )
}

export default Hero;

I am fetching the data in one JSX component and displaying it in another. I am passing the data to another jsx component like this:

<Search data={data} />

Here is table view component:

import React from 'react'
import Header from '../../components/Header/Header'
import Footer from '../../components/Footer/Footer'
import './Search.css'

const Search = ({ data }) =>{
        return (
            <div>
              <Header />
              <div id="page">
                <div className="container">
                    <section className="search-result-sec">
                        <div className="flex-row">
                            <div className="col-2">
                             <div className="banner-ad">
                                <p>Banner Ad</p>
                            </div>
                        </div>
                        <div className="col-8">
                            <div className="search-results">
                                {data && data.length > 0 ? (
                                <table>
                                    <thead>
                                        <tr>
                                            <th>Href</th>
                                            <th>Product Name</th>
                                            <th>Price</th>
                                            <th>PPU</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    {data.map((itemData, index) => (
                                    <tr key={index}>
                                        <td>{itemData.href}</td>
                                        <td>{itemData.name}</td>
                                        <td>{itemData.ppu}</td>
                                        <td>{itemData.price}</td>
                                    </tr>
                                    ))}
                                    </tbody>
                                </table>
                                ) : (
                                    <h2>No data available</h2>
                                  )}
                            </div>
                        </div>
                        <div className="col-2">
                         <div className="banner-ad">
                            <p>Banner Ad</p>
                        </div>
                    </div>
                </div>
            </section>
        </div>
        </div>
              <Footer />
            </div>
          )
    }

export default Search

Every time when I try to fetch the data, the code logs the data into console and load the next page but shows No data Available because its not getting any data in this page. Someone Please help me what I’m doing wrong here.

2

Answers


  1. First, add a console for data in the Search component and see if you are getting the data there. Also, make sure you are setting the right data coming from the response in the data state. Check if you are getting an array in the response from this code.

    axios
              .get(apiUrl)
              .then((response) => {
                // Handle the fetched data (e.g., update state to display it in the table)
                setData(response.data);
                console.log(response.data);
                history('/search');
                return response;
              })

    Maybe the response.data is returning an object that contains the array and not the array directly.

    If this doesn’t please provider more context or possiblily console.log the response and share that result.

    Login or Signup to reply.
  2. It seems like the issue might be related to the timing of fetching the data and rendering the Search component. When you fetch the data using the API and update the data state in the Hero component, it causes a re-render. However, at this point, the Search component might already be rendered without receiving the updated data prop.
    you are using history('/search') after setting the data in the state. Instead, you should use history.push('/search') to navigate to the search page after the data is fetched and the state is updated

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