Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

102
Vistas
Data coming but not showing in react

I am fetching some data from the backend and data is fetched without any errors, but the problem is that before the data is fetched, the HTML part is getting loaded and that's why data is not showing on the page. This may be a simple problem, but as a beginner, I don't know how to resolve this.

import React from "react";
import styled from "styled-components";
import HospitalCard from "../components/HospitalCard";
import SearchBar from "../components/SearchBar";
import { useState } from "react";
import { useEffect } from "react";
import axios from "axios";

const Container = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-direction: row;
  flex-wrap: wrap;
  padding: 2vh 5vw;
  margin: auto;
`;

function Home() {
  const nothing = <div>Nothing to show</div>;

  const [data, setData] = useState([]);

  const [Hospitals, setHospitals] = useState([]);

  const [filtered, setFiltered] = useState(false);

  const [searchItem, setSearchItem] = useState("");

  const getSearchValue = (e) => {
    setSearchItem(e);
  };

  useEffect(() => {
    let isMount = true;
    axios.get("http://localhost:4000/search").then((response) => {
      if (isMount) {
        const hdata = response.data;
        setHospitals(hdata);
        console.log(hdata);
        console.log(Hospitals);
      }
    });
    return () => {
      isMount = false;
    };
  }, []);

  useEffect(() => {
    setFiltered(true);
    var filteredHospitals = Hospitals.filter(function (el) {
      console.log(el.city);
      return (
        el.city.toLowerCase().includes(searchItem.toLowerCase().trim()) ||
        el.hospitalname
          .toLowerCase()
          .trim()
          .includes(searchItem.toLowerCase().trim()) ||
        el.state.toLowerCase().includes(searchItem.toLowerCase().trim())
      );
    });
    setData(filteredHospitals);
  }, [searchItem]);

  console.log(Hospitals);
  return (
    <div>
      <SearchBar style={{ margin: "auto" }} getSearchValue={getSearchValue} />
      <Container>
        {filtered
          ? data
            ? data.map((hospital) => {
                return (
                  <HospitalCard
                    key={hospital.mobilenumber}
                    hospital={hospital}
                  />
                );
              })
            : nothing
          : Hospitals.map((hospital) => {
              return (
                <HospitalCard key={hospital.mobilenumber} hospital={hospital} />
              );
            })}
      </Container>
    </div>
  );
}

export default Home;
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I think that you should simplify the way you handle filtering by removing the filtered flag and using an array to store the data to display in both cases.

  1. Create a filteredHospitals state to contain the data to be displayed
  2. When filtering update the data of this value
  3. Use conditional rendering to display the data if present

Finally, i think that you should change your getSearchValue code to setSearchItem(e.target.value) (You were using setSearchItem(e)).
The code of the SearchBar component is not included but I guess that the e parameter refers to the on change event object.

function Home() {
  const [Hospitals, setHospitals] = useState([]);
  const [filteredHospitals, setFilteredHospitals] = useState([]);

  const [searchItem, setSearchItem] = useState('');

  const getSearchValue = (e) => {
    setSearchItem(e.target.value);
  };

  useEffect(() => {
    let isMount = true;
    axios.get('http://localhost:4000/search').then((response) => {
      if (isMount) {
        const hdata = response.data;
        setHospitals(hdata);
        setFilteredHospitals(hdata);
      }
    });
    return () => {
      isMount = false;
    };
  }, []);

  useEffect(() => {
    var filteredHospitals = Hospitals.filter(function (el) {
      console.log(el.city);
      return (
        el.city.toLowerCase().includes(searchItem.toLowerCase().trim()) ||
        el.hospitalname
          .toLowerCase()
          .trim()
          .includes(searchItem.toLowerCase().trim()) ||
        el.state.toLowerCase().includes(searchItem.toLowerCase().trim())
      );
    });
    setFilteredHospitals(filteredHospitals);
  }, [searchItem]);

  console.log(Hospitals);

  return (
    <div>
      <SearchBar style={{ margin: 'auto' }} getSearchValue={getSearchValue} />
      <Container>
        {filteredHospitals && filteredHospitals.length > 0 ? filteredHospitals.map((hospital) => {
                return (
                  <HospitalCard
                    key={hospital.mobilenumber}
                    hospital={hospital}
                  />
                );
              }) : 'No data...'}
      </Container>
    </div>
  );
}

export default Home;
about 4 years ago · Juan Pablo Isaza Denunciar

0

You should use conditional render. Read this guide https://reactjs.org/docs/conditional-rendering.html

{filtered != undefined ? filtered?data?data.map((hospital) => {
                return <HospitalCard key={hospital.mobilenumber} hospital={hospital}/>
            }):nothing:Hospitals.map((hospital) => {
                return <HospitalCard key={hospital.mobilenumber} hospital={hospital}/>
            }) }
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda