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

use-axios-http-requests-ts

v1.1.4

Published

Incredibly useful package for making HTTP requests! This package eliminates the need for the Fetch API and is built on top of the powerful library [axios](https://www.npmjs.com/package/axios).

Downloads

38

Readme

use-axios-http-requests-ts

Incredibly useful package for making HTTP requests! This package eliminates the need for the Fetch API and is built on top of the powerful library axios.

With useAxios* hooks offered by use-axios-http-request, you no longer need to create separate states for results, errors, and loading states—everything is handled for you seamlessly!

Features

Special hooks:

| hook | description | | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------ | | useAxios | returns an [API response] object containing data from the API, as well as error and loading states. | | useAxiosFn | This function version of axios returns an [API response] Object, including an execute function when invoked automitically triggers the API |

What matters

  1. parameters

| parameter | type | description | optional | | -------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | | url | string | API string | false | | options | OptionsType | The OptionsType defined below comprises the parameters for making API requests, which include a set of properties can seen in the exmaple below. | true | | params | Object | Object of parameters you want to pass (as we pass like this ?page=1 in the url) we can do the same with the params object - {page:1,...} which is the params object | true | | dependencies | Array | Array of values when changed wiil fire the API again, default is empty = [] this means only once the API gets triggred even if appication states changes | true |

  1. return-values

| parameter | hook | description | | ------------ | ------------------------- | -------------------------------------------------------------------------------------------- | | data | useAxios + useAxiosFn | data from an API when request is successfull | | loading | useAxios + useAxiosFn | loading state | | error | useAxios + useAxiosFn | error response/object of type ErrorType defined below when request failes or error occured | | execute | useAxiosFn | A custom function which gaves control over when the API call will be trigger | | refetching | useAxiosFn | Function which sets the loading to true and data object to null | | reset | useAxiosFn | Resets all the states to their default values Error: null, data: null, loading: false |

Types

type OptionsType = {
  method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH",
  params?: Object,
  headers?: Object,
};

type ErrorType = {
  status?: number,
  message: string,
};

Installation*

npm

npm install use-axios-http-requests-ts

yarn

yarn add use-axios-http-requests-ts

Exmaple with Javascript

App.jsx

import { useAxios, useAxiosFn } from "use-axios-http-requests-ts";

const Products = () => {
  const PRODUCTS_URL = "https://dummyjson.com/products";
  const SEARCH_PRODUCTS_URL = "https://dummyjson.com/products/search";

  const { data: productsData, error, loading } = useAxios(URL);

  const [query, setQuery] = useState("");

  const {
    execute: SearchProducts,
    data: SearchedData,
    error,
    loading,
  } = useAxiosFn(SEARCH_PRODUCTS_URL, {
    params: {
      q: query,
    },
    [query]
  }); // takes 3 arguments api endpoint, options Object, dependency array

  useEffect(() =>{
    SearchProducts()
  },[query])

  const handleSearchInput = (e) => {
    setQuery(e.target.value);
  };

  // We can observe the search results updating in the log below whenever the query changes by invoking the SearchProducts() function inside a useEffect hook.
  console.log('Searched products: ', SearchProducts.products)

  return (
    <div className={styles.container}>
      <div className={styles.searchBox}>
        <label htmlFor="search">Search Products</label>
        <input
          autoComplete="off"
          autoCorrect="false"
          type="search"
          name="search"
          id="search"
          value={query}
          onChange={handleSearchInput}
        />
      </div>
      <div className={styles.products}>
        {loading ? (
          <>Loading..</>
        ) : (
          !error &&
          productsData?.products.map((p) => (
            <div key={p.id} className={styles.product}>
              <div className={styles.image}>
                <img src={p.thumbnail} alt={p.title} />
              </div>
              <div className={styles.desc}>
                <h4>{p.title}</h4>
                <p>{p.description}</p>
              </div>
            </div>
          ))
        )}
        {!loading && error && <div className={styles.error}>{error}</div>}
      </div>;
    </div>
  );
};

The only drawback of the approach using JavaScript is that we lack accessibility to data or suggestions for our data properties which can clearly seen below which force us to check the data coming from the API again and again!

but solution is there for every problem This can be overcome by using useAxios* hooks inside ts files, below is the difference we will find in ts over js!

Just your App.jsx file to App.tsx make sure you have all the typescript configurations done and installed typescript as dev dependencies pass the generic type of your expected data type from your API in the useAxios* hook just like shown below!

Exmaple with Typescript (minute changes)

type ProductsResponse = {
  products: any[];
  total: number;
  limit: number;
  skip: number;
};
const {
  data: productsData,
  error,
  loading,
} = useAxios<ProductsResponse>(PRODUCTS_URL);

Boom! with TypeScript, you gain additional superpowers, as you have access to all the properties present inside the data object now!

Happy hacking

🚀 Follow author

github linkedin twitter