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-redaxios

v1.3.9

Published

Simple & small react hook for making http request

Downloads

42

Readme

Features

  • Simple caching 📝
  • 9kb size 🗜️
  • Request interceptors 🔑
  • Typescript support

Table of contents

Simple usage

Simple usage with dependencies

It's like useEffect with its dependencies, will request the relative url when the passed objects change. The equality is deep

import { useRedaxios } from "use-redaxios";

const [count, setCount] = useState(1);

const { data, loading, error } = useRedaxios<object>(
    "https://jsonplaceholder.typicode.com/posts/" + count,
    {
        onSuccess: data => {
            // Do something
        },
        onError: response => {
            // Handle error
        },
    },
    // fire on dependency changes
    [count]
);

return <div>data: {JSON.stringify(data)}</div>;

Simple usage without dependencies

With this example you'll have to manually fire the requests

import { useRedaxios } from "use-redaxios";

const [count, setCount] = useState(1);

const { data, loading, error, get } = useRedaxios<object>(
    "https://jsonplaceholder.typicode.com/posts/",
    { onSuccess: () => console.log("success") }
);

// will only request when this callback has been called
const fire = () => {
    // this will change the data var as well
    const res = get("relative path");
};

return <div>data: {JSON.stringify(data)}</div>;

Advanced usage examples

POST'ing body with dependencies

Same as GET, but just with a body (sometimes useful)

import { useRedaxios } from "use-redaxios";

// changing data, use useState(obj) here
const body = {
    foo: "bar",
};

const {
    data = {},
    loading,
    error,
    get,
} = useRedaxios<object>(
    "https://jsonplaceholder.typicode.com/posts/" + count,
    {
        onSuccess: () => console.log("success"),
        axios: {
            method: "post",
            data: body,
        },
    },
    [count]
);

Default options with provider

You can set the the default options with a context provider:

import { RedaxiosProvider } from "use-redaxios";

ReactDOM.render(
    <RedaxiosProvider
        options={{
            interceptors: {
                // useful for authorization keys
                request: async request => {
                    return await { ...request };
                },
            },
            axios: {},
            onSuccess: () => console.log("yes"),
            onError: () => console.log("error"),
        }}
    >
        <Test />
    </RedaxiosProvider>,
    document.getElementById("root")
);

Note: these default options will be overwritten using a deep merge when you pass the options into the hook

How caching works

Here is the gist of it 😎:

  • A new request has been initiated
  • A new key will be generated based on:
    • The request's type
    • The request's body
    • The request's complete url
    • The useRedaxios dependencies
    • The useRedaxios options
  • Then the cache will be checked for this key
  • This key exists:
    • Set loading to false, but don't cancel the request
    • Check if the data from the request is deeply equal to the cache
    • It is equal:
      • No action
    • It is not equal:
      • Set the updated cache on this key
  • This key doesn't exist:
    • Continue the request normally, at the end set the cache

Documentation

Return objects

const { data, loading, fetching, error, get, del, patch, post, put } =
    useRedaxios<object>("url");

| Object | Type | Returns | | ---------- | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | data | unknown or a generic type that is passed into the useRedaxios hook | Returns the response body | | loading | boolean | Returns a boolean which will be true if the cache is empty, request is currently pending | | fetching | boolean | Returns a boolean which will be true if the request is currently pending, cache doesn't matter | | error | Response | Returns the whole failed response | | get | BodylessMethod | Returns a function that will manually GET request the supplied url, you can pass another url to it that will get added on top of the supplied one | | del | BodylessMethod | Returns a function that will manually DELETE request the supplied url, you can pass another url to it that will get added on top of the supplied one | | patch | BodyMethod | Returns a function that will manually PATCH request the supplied url, you can pass a request body and another url to it that will get added on top of the supplied one | | post | BodyMethod | Returns a function that will manually POST request the supplied url, you can pass a request body and another url to it that will get added on top of the supplied one | | put | BodyMethod | Returns a function that will manually PUT request the supplied url, you can pass a request body and another url to it that will get added on top of the supplied one |

Passing options

Option interface currently looks like this

export interface useRedaxiosOptions<Body> {
    interceptors?: {
        request?: (request: Options) => Promise<Options>;
        response?: (body: Body) => Promise<any>;
    };
    onSuccess?: (res: Body) => void;
    onError?: (error: Response<any>) => void;
    axios?: Options;
}

| Option | More info | | ---------------------- | ------------------------------------------------------------------------------------------------------ | | interceptors.request | Pass an async function that will be called before every request, it must return the modified options |

Request interceptor example

interceptors: {
    request: async request => {
        return {
            ...request,
            headers: {
                ...request.headers,
                Authorization: await "Some key",
            },
        };
    },
},

| Option | More info | | ---------------------- | ------------------------------------------------------------------------------------------------------------------------- | | interceptor.response | Pass an async function that will be called every time the request succeeds, it must return the modified response body |

Response interceptor example

interceptors: {
    response: async data => {
        console.log(data);
        return {
            ...data,
            foo: await bar
        };
    },
},

| Option | More | | ----------- | ------------------------------------------------------------------------------------------------------ | | onSuccess | This function (callback) will be called with the response's body when the response has been successful | | onError | This function (callback) will be called with the whole response when the response has failed | | axios | Pass in additional request options, api is very similar to the native fetch options |