How to show search result not found message

Solution for How to show search result not found message
is Given Below:

import React, { useState, useEffect } from 'react'
import axios from 'axios'

function DataApi({ searchTerm }) {
  const [users, setUsers] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState()

  useEffect(() => {
    axios
      .get('https://jsonplaceholder.typicode.com/posts')
      .then(res => {
        setUsers(res.data);
        console.log(res.data);
        setLoading(true);
      })
      .catch(error => {
        console.log(error);
        setError('Error retrieving data');
      });
  }, []);
  return (
    <div>
      <div>
        {
          !loading ?
          <h1>...Loading</h1>
          :
          users.length > 0 && users.filter((item) => 
            (searchTerm === '') ?  item :
            (item.title.toLowerCase().includes(searchTerm.toLocaleLowerCase())) ? item :
            // <h1>search result not found</h1>
            null
          ).map((item) => {
          return (
          <ul key={item.id}>
            <li>Name: {item.id}</li>
            <li>Title: {item.title}</li>
            <li>Body: {item.body}</li>
          </ul>
            )}
            )
          }
          {
            error ? <h1>{error}</h1> : null
          }
      </div>
    </div>
  )
}

export default DataApi;

I have made a search field in which user can search the name of the person. If user does not get the searched name then there should be a message come that search result not found. I tried to implement it using if-else (ternary operator) & put the message into else part but it is not working. When I put null instead of search result not found then it works perfectly but I am not able to show the message then. But if I put search result not found instead of null then nothing works, not even filter functionality. Can you guys please help me? Thank you in advancve.

You can simply check the length of user and move the filter method to the useEffect and show a message

import React, { useState, useEffect } from "react";
import axios from "axios";

function DataApi({ searchTerm }) {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState();
  const [searchTermTest, setsearchTermTest] = useState();

  function handleChange(event) {
    setsearchTermTest(event.target.value);
  }
  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/posts")
      .then((res) => {
        const data = res.data;
        const filteredData = data.filter((dat) =>
          dat.title.includes(searchTermTest === undefined ? "" : searchTermTest)
        );
        setUsers(filteredData);
        setLoading(true);
      })
      .catch((error) => {
        console.log("errr", error);
        setError("Error retrieving data");
      });
  }, [searchTermTest]);

  return (
    <div>
      <input type="text" onChange={handleChange} />
      <div>
        {!loading ? (
          <h1>...Loading</h1>
        ) : (
          users.length > 0 &&
          users.map((item) => {
            return (
              <ul key={item.id}>
                <li>Name: {item.id}</li>
                <li>Title: {item.title}</li>
                <li>Body: {item.body}</li>
              </ul>
            );
          })
        )}
        {users.length === 0 && loading ? <h1>search result not found</h1> : ""}
        {error ? <h1>{error}</h1> : null}
      </div>
    </div>
  );
}

export default DataApi;



        {users.length === 0 && loading ? <h1>search result not found</h1> : ""}

I have made it in codesandbox

Codesandbox link here

In Array.filter() method you need to return true/false value, that’s how it works.

Modified the code and added the renderUser function to take care of user data filter.

DataApi function

function DataApi({ searchTerm }) {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState();
  const [searchTermTest, setsearchTermTest] = useState();

  function handleChange(event) {
    setsearchTermTest(event.target.value);
  }
  useEffect(() => {
    axios
      .get("https://jsonplaceholder.typicode.com/posts")
      .then((res) => {
        const data = res.data;
        const filteredData = data.filter((dat) =>
          dat.title.includes(searchTermTest === undefined ? "" : searchTermTest)
        );
        setUsers(filteredData);
        setLoading(true);
      })
      .catch((error) => {
        console.log("errr", error);
        setError("Error retrieving data");
      });
  }, [searchTermTest]);

  return (
    <div>
      <input type="text" onChange={handleChange} />
      <div>
        {!loading ? (
          <h1>...Loading</h1>
        ) : (
          users.length > 0 && renderUsers(users, searchTerm) // updated here...
        )}
        {error ? <h1>{error}</h1> : null}
      </div>
    </div>
  );
}

renderUsers function

const renderUsers = (users, searchTerm) => {
  const filteredUsers = users.filter((item) => {
    console.log(item.title);
    return searchTerm === ""
      ? true
      : item.title.toLowerCase().includes(searchTerm.toLocaleLowerCase())
      ? true
      : false;
  });
  return filteredUsers.length > 0 ? (
    filteredUsers.map((item) => {
      return (
        <ul key={item.id}>
          <li>Name: {item.id}</li>
          <li>Title: {item.title}</li>
          <li>Body: {item.body}</li>
        </ul>
      );
    })
  ) : (
    <h1>search result not found</h1>
  );
};

export default DataApi;