1.3.9 • Published 2 years ago

use-redaxios v1.3.9

Weekly downloads
-
License
UNLICENSE
Repository
github
Last release
2 years ago

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");
ObjectTypeReturns
dataunknown or a generic type that is passed into the useRedaxios hookReturns the response body
loadingbooleanReturns a boolean which will be true if the cache is empty, request is currently pending
fetchingbooleanReturns a boolean which will be true if the request is currently pending, cache doesn't matter
errorResponseReturns the whole failed response
getBodylessMethodReturns 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
delBodylessMethodReturns 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
patchBodyMethodReturns 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
postBodyMethodReturns 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
putBodyMethodReturns 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;
}
OptionMore info
interceptors.requestPass 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",
            },
        };
    },
},
OptionMore info
interceptor.responsePass 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
        };
    },
},
OptionMore
onSuccessThis function (callback) will be called with the response's body when the response has been successful
onErrorThis function (callback) will be called with the whole response when the response has failed
axiosPass in additional request options, api is very similar to the native fetch options
1.3.9

2 years ago

1.3.7

3 years ago

1.3.6

3 years ago

1.3.5

3 years ago

1.3.8

3 years ago

1.3.4

3 years ago

1.3.3

3 years ago

1.3.2

3 years ago

1.2.3

3 years ago

1.3.1

3 years ago

1.2.2

3 years ago

1.3.0

3 years ago

1.2.31

3 years ago

1.2.34

3 years ago

1.2.12

3 years ago

1.2.35

3 years ago

1.2.32

3 years ago

1.2.33

3 years ago

1.2.11

3 years ago

1.2.0

3 years ago

1.2.1

3 years ago

1.1.34

3 years ago

1.1.33

3 years ago

1.1.32

3 years ago

1.1.31

3 years ago

1.1.3

3 years ago

1.1.22

3 years ago

1.1.21

3 years ago

1.1.2

3 years ago

1.1.13

3 years ago

1.1.12

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.0.13

3 years ago

1.0.12

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago