1.1.4 • Published 1 year ago

use-axios-http-requests-ts v1.1.4

Weekly downloads
-
License
ISC
Repository
-
Last release
1 year ago

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:

hookdescription
useAxiosreturns an API response object containing data from the API, as well as error and loading states.
useAxiosFnThis function version of axios returns an API response Object, including an execute function when invoked automitically triggers the API

What matters

  1. parameters
parametertypedescriptionoptional
urlstringAPI stringfalse
optionsOptionsTypeThe OptionsType defined below comprises the parameters for making API requests, which include a set of properties can seen in the exmaple below.true
paramsObjectObject 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 objecttrue
dependenciesArrayArray of values when changed wiil fire the API again, default is empty = [] this means only once the API gets triggred even if appication states changestrue
  1. return-values
parameterhookdescription
datauseAxios + useAxiosFndata from an API when request is successfull
loadinguseAxios + useAxiosFnloading state
erroruseAxios + useAxiosFnerror response/object of type ErrorType defined below when request failes or error occured
executeuseAxiosFnA custom function which gaves control over when the API call will be trigger
refetchinguseAxiosFnFunction which sets the loading to true and data object to null
resetuseAxiosFnResets 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

1.1.4

1 year ago

1.1.3

1 year ago

1.0.2

1 year ago

1.1.1

1 year ago

1.0.0

1 year ago

1.0.3

1 year ago

1.1.2

1 year ago

1.0.1

1 year ago