Home > Back-end >  How to do i deal with API returning data when query is empty?
How to do i deal with API returning data when query is empty?

Time:10-25

I'm fetching data from an API and displaying it on the front end of my website

{/*fetching the the data from an API*/}
  function searchArtistes() {
    const options = {
      method: "GET",
      headers: {
        "X-RapidAPI-Key": "86f453f970msh48154777add2da0p1e185cjsn969596f1a317",
        "X-RapidAPI-Host": "spotify81.p.rapidapi.com",
      },
    };

    fetch(
      `https://spotify81.p.rapidapi.com/search?q=${searchInput}&type=multi&offset=0&limit=10&numberOfTopResults=5`,
      options
    )
      .then((response) => response.json())
      .then((response) =>
        setArtisteData(
          response.artists.items.map((artist) => artist.data.profile.name)
        )
      )
      .catch((err) => console.error(err));
  }
{/* function fetching the data is called by an onChange event listener in the input */}
          <form className="search-input flex justify-between  md:items-center">
            <div className="flex md:flex-row-reverse">
              <input
                placeholder="search artists"
                onChange={() => {
                  handleChange(event);
                  searchArtistes();
                }}
                className="search ml-6 "
              />
              <img
                src={search}
                className="search-icon md:ml-12 lg:ml-14 2xl:ml-18"
              />
            </div>
          </form>


{/*Displaying it on the interface*/}
        <div>
          <ul className="flex flex-col items-center text-white">
            {artisteData.map((name) => (
              <li className="cursor-pointer pt-1">{name}</li>
            ))}
          </ul>
        </div>

But the problem is even when the query is empty the api still returns data as seen in the image below:

enter image description here

What can i do about this?

CodePudding user response:

It's because an empty string is still a string when it comes to query parameters. In all the cases that I know of, a search for the text "" would simply return unfiltered results, and not prevent your code from sending the API call itself. It's on you to keep track of the state of the search input's value, and restrain from sending the API query when it's empty.

But then, your code has far more serious problems to worry about as well. For one, you're sending API calls out every time search input changes, which is a severe waste of resources. Keep track of search text changes locally, and send out the API query only when the user submits the search query.

Or if you want the results to update dynamically as the user types in the query, fetch the unfiltered results, store them locally, and filter them locally as the query text changes in the UI.

CodePudding user response:

Set the state of you initial artisteData to null as follow with the useState() hook if this is a functional component:

const [artisteData, setArtisteData] = useState(null);

The idea is to set the state to the data only once it has data.

Add the "?" operator before the .map. This checks if the array is empty before running through the dataset

Try this:

<div>
    <ul className="flex flex-col items-center text-white">
        {artisteData?.map((name) => (
            <li className="cursor-pointer pt-1">{name}</li>
         ))}
    </ul>
</div>

Edit:

I also need to mention that calling the function on change is a waste of resources. Call this onSubmit() with a button instead.

If this is still the approach you want to take (which I do not advise) you can always implement it as follow:

<div>
    <ul className="flex flex-col items-center text-white">
        {artisteData?.map((name) => (
            if(name !== null and name !== "")
            <li className="cursor-pointer pt-1">{name}</li>
         ))}
    </ul>
</div>

This checks if the Artist name is empty before creating the element in the DOM.

  • Related