Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

103
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda