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

116
Visualizações
Return "No Data Found" in search functionality in React js

I am having trouble with React js. I am implementing search functionality. Everything is good but I want to show if the term entered in the search bar is not available. It should show "No Data Found". I have also attached the screenshot.

Search Component

const UserDetails = () => {
  const [posts, setPosts] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");

  useEffect(() => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => setPosts(data.results));
  }, []);

  return (
    <>
      <div className="Navbar">
        <img className="logo" src={logo} alt="" />
        <input
          type="text"
          onChange={(event) => {
            setSearchTerm(event.target.value);
          }}
          placeholder="Search User.."
        ></input>
      </div>

      <div className="card">
        {posts.length > 0 ? (
          posts
            .filter((val) => {
              if (searchTerm === "") {
                return val;
              } else if (
                val.name.first
                  .toLowerCase()
                  .includes(searchTerm.toLowerCase()) ||
                val.name.last.toLowerCase().includes(searchTerm.toLowerCase())
              ) {
                return val;
              }
            })
            .map((post, index) => <Userdetail key={index} post={post} />)
        ) : (
          <div className="loading">
            <img src={logo} className="App-logo" alt="logo" />
            <p className="loading-data">Loading Data...</p>
          </div>
        )}
      </div>
    </>
  );
};

export default UserDetails;

Screenshot

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are checking if posts has values, and if it doesn't it should show loading div. This is the place where you should add "No data found" and for the loading you should set state to indicate loading status.

I have modified your code a bit

const UserDetails = () => {
  const [posts, setPosts] = useState([]);
  const [searchTerm, setSearchTerm] = useState("");
  const [loading,setLoading] = useState(false) // loading state

  useEffect(() => {
    setLoading(true); // loading started
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        setPosts(data.results);
        setLoading(false); // loading stopped
      })
      .catch((e) => {
        setLoading(false); // loading stopped
        console.log(e);
      });
  }, []);

  return (
    <>
      <div className="Navbar">
        <img className="logo" src={logo} alt="" />
        <input
          type="text"
          onChange={(event) => {
            setSearchTerm(event.target.value);
          }}
          placeholder="Search User.."
        ></input>
      </div>

      <div className="card">
        {loading ? ( // loading state
          <div className="loading">
            <img src={logo} className="App-logo" alt="logo" />
            <p className="loading-data">No data</p>
          </div>
        ) : posts.length > 0 ? (
          posts
            .filter((val) => {
              if (searchTerm === "") {
                return val;
              } else if (
                val.name.first
                  .toLowerCase()
                  .includes(searchTerm.toLowerCase()) ||
                val.name.last.toLowerCase().includes(searchTerm.toLowerCase())
              ) {
                return val;
              }
            })
            .map((post, index) => <Userdetail key={index} post={post} />)
        ) : (
          <p>No data found!</p>
        )}
      </div>
    </>
  );
};

export default UserDetails;

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