1.2.1 • Published 3 years ago

ratios v1.2.1

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

Ratios

A React hook library for managing axios requests, includes cancellation mechanism.

Installation

  • If you're using yarn: yarn add ratios
  • If you're using npm: npm install ratios --save

Demo

See live demo on Stackblitz.

For more information about why we should cancel a request before component unmounts, please see this article.

Basic usage

1. First, manage your axios requests in a proper way

// File: /src/apis/user.js
import axios from "axios";

const instance = axios.create({
  baseURL: "/api/users",
  headers: {
    "Content-Type": "application/json",
  },
  // ...
});

const UserAPI = {
  getAll: (config) => instance.get("", config),
  create: (data) => (config) => instance.post("", data, config),
  updateById: (id, data) => (config) => instance.put(`/${id}`, data, config),
  deleteById: (id) => (config) => instance.delete(`/${id}`, config),
};

export default UserAPI;

2. Import the "useAxiosRequest" hook from Ratios, and use one of the axios requests we just created as argument

import React from "react";
import { useAxiosRequest } from "ratios";
import UserAPI from "../apis/user";

const MyComponent = () => {
  const getUsersRequest = useAxiosRequest(UserAPI.getAll);

  return (
    <div>
      {getUsersRequest.isLoading ? (
        "Loading..."
      ) : (
        <ol>
          {getUsersRequest.data.map((user) => (
            <li key={user.id}>{user.name}</li>
          ))}
        </ol>
      )}
    </div>
  );
};

export default MyComponent;

And that's it! The hook will cancel the request for you when the component unmounts.

Advanced usage

1. With custom config (e.g, query parameters)

import React, { useState } from "react";
import { useAxiosRequest } from "ratios";
import UserAPI from "../apis/user";

const MyComponent = () => {
  const [filter, setFilter] = useState({
    name: "",
    age: 5,
  });

  const getUsersRequest = useAxiosRequest((cancelTokenConfig) =>
    UserAPI.getByQuery({
      ...cancelTokenConfig,
      params: filter,
    })
  );

  // Your other codes
};

2. With custom arguments (e.g, create user)

import React, { useState } from "react";
import { useAxiosRequest } from "ratios";
import UserAPI from "../apis/user";

const MyComponent = () => {
  const [form, setForm] = useState({
    name: "John Doe",
    age: 10,
  });

  const createUserRequest = useAxiosRequest(UserAPI.create(form), {
    defaultIsLoading: false,
    immediate: false,
    onError: handleError,
  });

  const handleSubmitClick = async () => {
    const createdUser = await createUserRequest.execute();
    console.log("Created user: ", createdUser);
  };

  const handleError = (error) => {
    console.log("Something went wrong.");
    console.error(error);
  };

  // Your other codes
};

3. useCancelTokenSource hook

If you just want to apply cancellation mechanism to your existing app, you can use the "useCancelTokenSource" hook.

import { useCancelTokenSource } from "ratios";

const MyComponent = () => {
  const cancelTokenSource = useCancelTokenSource();

  const myFunction = async () => {
    try {
      const { data } = await myAPI.getSomething({
        cancelToken: cancelTokenSource.token,
      });
      console.log(data);
    } catch (error) {
      if (cancelTokenSource.isCancelError(error)) {
        console.log("Request is cancelled.");
      } else {
        throw error;
      }
  };

  // Your other codes
};

The request will be cancelled automatically when component unmounts.

API

1. Properties for useAxiosRequest()

keyTypeDescription
isLoadingbooleanIf the request is still going on.
data<T = any>The data property returned from axios response.
setData(callback: (prevData: T) => T)The function to update data.
executedbooleanIf the request has been executed.
execute() => Promise<T>Execute the request manually. If the isLoading property is still true, then it will NOT execute the request. Will return the data property from axios response if success.

2. Options for useAxiosRequest()

keyTypeRequiredDefault ValueDescription
defaultIsLoadingbooleanfalsetrueThe default value of request.isLoading.
defaultDataanyfalseundefinedThe default value of request.data.
immediatebooleanfalsetrueIf the request should be executed immediately after the component is mounted.
cancelPreviousbooleanfalsetrueIf the previous request should be cancelled before executing a new one.
onSuccess(data: T) => anyfalseundefinedFunction to execute when API is successfully executed.
onError(error: any) => anyfalseundefinedFunction to execute when an error occurred during API execution.
onCancelled(error: any) => anyfalseundefinedFunction to execute when the request is cancelled.

3. Properties for useCancelTokenSource()

keyTypeDescription
tokenCancelTokenThe cancel token.
cancel() => CancelToken | undefinedReturn next token if repeatable is true, else return undefined.
isCancelError(value: any) => booleanUse this method to check if an error is thrown due to cancellation. This method equals to axios.isCancel.

4. Options for useCancelTokenSource()

keyTypeRequiredDefault ValueDescription
repeatablebooleanfalsetrueIf the token can be used multiple times.
1.2.0

3 years ago

1.2.1

3 years ago

1.1.9

3 years ago

1.1.8

3 years ago

1.1.7

3 years ago

1.1.6

3 years ago

1.1.5

3 years ago

1.1.4

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.0.9

3 years ago

1.1.3

3 years ago

1.1.2

3 years ago

1.0.10

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago