npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

search-optimization

v1.1.4

Published

npm package to optimize searching in web app

Downloads

1

Readme

search-optimzation

Attach debouncing and throttling to your search box in just one line of code where you can choose to cache the search result or not.

Features

  • This npm package provides two hooks namely useDebounce and useThrottle. Using this hooks you can apply debouncing and throttling to your search box

  • You can control the delay time of debouncing and throttling.

  • You can also decide whether you want to cache the result or not (it stores 10 results to save network call).

Installation

With npm:

  npm i search-optimization

With yarn

  yarn add search-optimization

Demo

To see useDebounce really working please click here ( the demo is fully automated ) and open network tab and observe network call happening. In this example the caching is on.

Usage

Create the async function which is fetching data. Function must return the response. Also your input or search box must be controlled by React.

useDebounce and useThrottle both hook accepts 4 arguments and they are an apiCallFunction, delay, a state variable that is controlling the input or search box and flag which is boolean value to make caching on and off.

useDebounce returns one object that has data and error property. data contains the returned result from fetch call and error contains error if API call fails. You can also give custom error in your async function as it is shown in below example.

useThrottle returns one object that has data, error and timerID property. data contains the returned result from fetch call and error contains error if API call fails. You can also give custom error in your async function as it is shown in below example. timerID is given because let say someone is applying on search box which is displaying the fetched result from API call in dropdown where clicking on anyone of those fetched result will redirected to another page and in this scenario if someone has provided delay of 2000 or more milliseconds (which is not the ideal case) and in that two seconds result are fetched and displayed and user has clicked on any one of those fetched result and redirected to another page. Now at this point of time unmounting of that component of the current page will happen as user is redirected to another page and one must take care of clearing the things while unmounting of the component. For this particular reason everytime timerID is returned so that at time of unmounting you can clear it.

Example


import { useState } from "react";
import { useDebounce } from "search-optimization";
export default function App() {
  const [query, setQuery] = useState("Bangalore");
  const { data, error } = useDebounce(fetchData, 500, query, true);
  async function fetchData() {
    const url = `https://api.api-ninjas.com/v1/weather?city=${query}`;
    const response = await fetch(url, {
      headers: {
        "Content-Type": "application/json",
        "X-Api-Key": process.env.REACT_APP_NINJA_API_KEY,
      },
    });

    /* Manytimes irrespective of bad response, say 404 or 500,
     API call will still fulfill the promise, to avoid that 
     one can check response.ok if it is false one can throw
     their own custom error
     If you don't do this explicitly then promise get fulfilled
     and it will pass error to data instead of passing it to
     error  */

    if (!response.ok) {
      throw new Error("Something went wrong");
    }
    const apiData = await response.json();
    // api call must return data
    return apiData;
  }

  const handleChange = (e) => {
    console.log(e?.target?.value);
    setQuery(e?.target?.value);
  };
  return (
    <div className="App">
      <input type="text" value={query} onChange={handleChange} />
      {data && (
        <div className="table">
          <span>Temperature:</span>
          <span>{data.temp}</span>
          <span>Feels Like:</span>
          <span>{data.feels_like}</span>
          <span>Humidity:</span>
          <span>{data.humidity}</span>
          <span>Wind speed:</span>
          <span>{data.wind_speed}</span>
        </div>
      )}
      {error && <p>{error.message}</p>}
    </div>
  );
}

You can clear timerID in following way as shown below


//....
const { data, error, timerID } = useThrottle(fetchData, 2000, value, true);

//....

useEffect(() => {
  return () => clearTimeout(timerID);
}, []);

//.....

return {
  /* ... */
};

Things to keep in mind💡

  • If you do not pass the first argument or first argument as function then hook will throw error in console.
  • If forget to pass second argument i.e. delay argument then by default delay time will be zero.
  • If you forget to return the fetched data from api call then hook will give error in error property of returned object from useDebounce or useThrottle hook.
  • If you forget to pass third argument i.e. state variable which is controlling input or search box it will throw an error in console.
  • If you forget to pass the fourth argument i.e. flag which turns on and off caching of the result fetched from an API call, by default caching value will be set to false.