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-ajax-request

v2.1.0

Published

A react hook used to manage http requests and responses in React Js applications

Downloads

16

Readme

USE-AJAX-REQUEST

Use-ajax-request is a javascript library capable of sending http requests to a server. It was built with the aim of aiding react-js developers managel less state when they want to send/get data from a server. This hook manages the data recieved from the response, the error recieved from the response, the funtion to be called inorder to send the http request and the isLoading state to verify if the request is still or is done loading.

Instalation

To install this package run npm install use-ajax-request OR yarn add use-ajax-request To install this a specific version run npm install use-ajax-request@version OR yarn add use-ajax-request@version. Replace version with the package version e.g 1.0.0

How to use the package

N.B: To use this package you MUST have react, react-dom and axios installed Import the package

import useAjaxRequest from "use-ajax-request";

Assign the hook to a constant variable (You can also destructure the variable). The useAjaxRequest hook always returns an object containing

{
     data: String,
    loading: Boolean,
    error: Boolean,
    sendRequest: Function
}

Therefore we can destructure it like this:

const { data, loading, error, sendRequest } = useAjaxRequest();

But before we go further the useAjaxRequestHook takes in an object which MUST be supplied. I.e

{
    instance: Function /* Axios instance or axios function */,
    options: {
    url: String,
    method: String,
    headers: Object,
    //...other axios properties
    }
}

The instance MUST contain either an axios instance OR an axios function, because that's going to be used to send the http request. The options contains the properties of the request, e.g: headers, url, method, etc...

After doing all these we should now have this in our code:

import useAjaxRequest from "use-ajax-request";

const { loading, data, sendRequest, error } = useAjaxRequest({
  instance: axios,
  options: {
    url: "https://somedomain.com/route",
    method: "GET",
  },
});

Then we execute the sendRequest function anytime we want to trigger the request. E.g

sendRequest();

Let's try calling it from a useEffectHook:

useEffect(() => {
  sendRequest();
}, []);

Sometimes it may require us to add the sendRequest function as a dependency in the array, in that case we would have to wrap the parameters we are passing into useAjaxRequest with a useMemo() hook to avoid an infinite loop. I.e:

import useAjaxRequest from "use-ajax-request";

const { loading, data, sendRequest, error } = useAjaxRequest(
  useMemo(() => {
    return {
      instance: axios,
      options: {
        url: "https://somedomain.com/route",
        method: "GET",
      },
    };
  }, [])
);

useEffect(() => {
  sendRequest();
}, [sendRequest]);

The data variable holds the result of the response if it encounted no errors:

console.log(data);
//False if no data else response data

The error variable holds the error of the request if it encounted an error, it returns false if they were no errors:

console.log(error);
//False if no error else request error

The loading variable returns the state of the request, True if it's still ongoing, false if it's done:

console.log(loading);
//False if done loading else request True

Then you can add some JSX code to verify if it's working correctly:

return (
  <div className="App">
    <header className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      {loading ? (
        <p>Loading...</p>
      ) : error ? (
        <p>There was an error</p>
      ) : !data ? (
        <p>No movies available</p>
      ) : (
        data?.results?.map((eachMovie) => (
          <div key={eachMovie?.episode_id}>
            <p>
              <b>Title:</b> {eachMovie?.value}
            </p>
            <p>
              <b>Episode:</b> {eachMovie?.value}
            </p>
            <p>
              <b>Opening:</b> {eachMovie?.value}
            </p>
            <p>
              <b>Date released:</b>
              {new Date()?.toUTCString()}
            </p>
          </div>
        ))
      )}
    </header>
  </div>
);

At the end our code should look like this:

import logo from "./logo.svg";
import "./App.css";
import useAjaxRequest from "use-ajax-request";
import { useEffect, useMemo } from "react";
import axios from "axios";

function App() {
  const { loading, data, sendRequest, error } = useAjaxRequest(
    useMemo(() => {
      return {
        instance: axios,
        options: {
          url: "https://swapi.dev/api/films",
          method: "GET",
        },
      };
    }, [])
  );
  error && console.log("ERROR", error);

  useEffect(() => {
    sendRequest();
  }, [sendRequest]);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        {loading ? (
          <p>Loading...</p>
        ) : error ? (
          <p>There was an error</p>
        ) : data?.results?.length < 1 ? (
          <p>No movies available</p>
        ) : (
          data?.results?.map((eachMovie) => (
            <div key={eachMovie?.episode_id}>
              <p>
                <b>Title:</b> {eachMovie?.title}
              </p>
              <p>
                <b>Episode:</b> {eachMovie?.episode_id}
              </p>
              <p>
                <b>Opening:</b> {eachMovie?.opening_crawl}
              </p>
              <p>
                <b>Date released:</b>
                {new Date(eachMovie?.release_date)?.toUTCString()}
              </p>
            </div>
          ))
        )}
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

N.B: We can also add onSuccess or onError functions, which will be called if we recieve a successfull response or we recieve an error respectively. E.g:

const onSuccess = () => {
  // ...perform something
};
const onError = () => {
  // ...perform something
};

useEffect(() => {
  sendRequest(onSuccess, onError);
}, [sendRequest]);

In order to pass a parameter to the respective functions we just need to add the .bind() function to them:

useEffect(() => {
  sendRequest(
    onSuccess.bind(null, parameter1, parameter2),
    onError.bind(null, parameter1, parameter2)
  );
}, [sendRequest]);

More features will be added to it in the future. Thank you. Please if you like it star the github repo or fork it. Thanks useAjaxRequest Repo