All Projects → sergey-s → use-axios-react

sergey-s / use-axios-react

Licence: other
React axios hooks for CRUD

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to use-axios-react

The Platform
Web. Components. 😂
Stars: ✭ 4,355 (+13948.39%)
Mutual labels:  react-hooks
Rxjs Hooks
React hooks for RxJS
Stars: ✭ 1,953 (+6200%)
Mutual labels:  react-hooks
Fre
👻 Tiny Footprint Concurrent UI library for Fiber.
Stars: ✭ 3,195 (+10206.45%)
Mutual labels:  react-hooks
Hooks
A high-quality & reliable React Hooks library.
Stars: ✭ 7,841 (+25193.55%)
Mutual labels:  react-hooks
Graphql Hooks
🎣 Minimal hooks-first GraphQL client
Stars: ✭ 1,610 (+5093.55%)
Mutual labels:  react-hooks
Use Http
🐶 React hook for making isomorphic http requests
Stars: ✭ 2,066 (+6564.52%)
Mutual labels:  react-hooks
Easy Peasy
Vegetarian friendly state for React
Stars: ✭ 4,525 (+14496.77%)
Mutual labels:  react-hooks
react-hooks-lifecycle
⚛️ 🪝 ⏳ React hooks lifecycle diagram: Functional components lifecycle explained
Stars: ✭ 194 (+525.81%)
Mutual labels:  react-hooks
React Cloud Music
React 16.8打造精美音乐WebApp
Stars: ✭ 1,722 (+5454.84%)
Mutual labels:  react-hooks
React Form
⚛️ Hooks for managing form state and validation in React
Stars: ✭ 2,270 (+7222.58%)
Mutual labels:  react-hooks
Awesome React Hooks
Awesome React Hooks
Stars: ✭ 7,616 (+24467.74%)
Mutual labels:  react-hooks
React Native Firebase
🔥 A well-tested feature-rich modular Firebase implementation for React Native. Supports both iOS & Android platforms for all Firebase services.
Stars: ✭ 9,674 (+31106.45%)
Mutual labels:  react-hooks
Haunted
React's Hooks API implemented for web components 👻
Stars: ✭ 2,197 (+6987.1%)
Mutual labels:  react-hooks
React Adaptive Hooks
Deliver experiences best suited to a user's device and network constraints
Stars: ✭ 4,750 (+15222.58%)
Mutual labels:  react-hooks
Project chat application
This is a code repository for the corresponding YouTube video. In this tutorial we are going to build and deploy a real time chat application. Covered topics: React.js, Node.js, Express.js, and Socket.io.
Stars: ✭ 2,966 (+9467.74%)
Mutual labels:  react-hooks
Beautiful React Hooks
🔥 A collection of beautiful and (hopefully) useful React hooks to speed-up your components and hooks development 🔥
Stars: ✭ 5,242 (+16809.68%)
Mutual labels:  react-hooks
React Firebase Hooks
React Hooks for Firebase.
Stars: ✭ 2,227 (+7083.87%)
Mutual labels:  react-hooks
react-7h-hooks
(持续增加中)提供一些偏业务的实用 react hooks, 让你每天只工作 7 小时 !
Stars: ✭ 15 (-51.61%)
Mutual labels:  react-hooks
Reactfire
Hooks, Context Providers, and Components that make it easy to interact with Firebase.
Stars: ✭ 2,908 (+9280.65%)
Mutual labels:  react-hooks
Mobx React Lite
Lightweight React bindings for MobX based on React 16.8 and Hooks
Stars: ✭ 2,096 (+6661.29%)
Mutual labels:  react-hooks
WARNING: not maintained, feel free to fork and use in any way

npm i axios use-axios-react

Features

  • Hooks for data fetching CRUD Batch operations
  • Request cancellation
  • Retry/reload callbacks
  • Zero-configuration, yet fully configurable when needed
  • No app architecture commitments, drop in into your React and Axios project and start using hooks in your new components
  • No extra-dependencies (React and Axios are peer dependencies), thus minimum overhead if your project already uses axios
  • All axios features

Installation

npm i use-axios-react

Make sure axios itself is installed

npm i axios

And make sure you use React v16.8.0 or newer.

Examples

Basic data fetching (GET)

Edit Fetch example

import React from "react";
import { useGetData } from "use-axios-react";

const KanyeQuote = () => {
  const [data, loading] = useGetData("https://api.kanye.rest/");

  if (loading) return <div>Loading...</div>;

  return <blockquote>{data.quote}</blockquote>;
};

Cancellable fetching (GET) with reload and retry

Edit Cancelable fetch with reload & retry

import React from "react";
import { useGetData } from "use-axios-react";

const KanyeQuote = () => {
  const [data, loading, { error, retry }] = useGetData("https://api.kanye.rest/", { cancelable: true });

  if (loading) return <Spinner />;
  if (error) return <Button onClick={retry} label="RETRY" />;

  return (
    <div>
      <Quote>{data.quote}</Quote>
      <Button onClick={retry} label="RELOAD" />
    </Fragment>
  );
};

Basic POST example

Edit POST example

import React from "react";
import { usePostCallback } from "use-axios-react";

function userToRequest({ name, job }) {
  return {
    url: "https://reqres.in/api/users",
    data: { name, job }
  };
}

const CreateUser = () => {
  const [create, sending, { error, data }] = usePostCallback(userToRequest);

  const neo = { name: "Neo", job: "The One" };
  const morpheus = { name: "Morpheus", job: "Leader" };

  return (
    <Layout>
      <Button onClick={() => create(neo)}>Neo</Button>
      <Button onClick={() => create(morpheus)}>Morpheus</Button>
      <StatusBar sending={sending} error={error} lastUser={data} />
    </Layout>
  );
};
Pagination

Edit Pagination

import React, { useState } from "react";
import { useGetData } from "use-axios-react";

const PaginatedKanyeQuotes = () => {
  const [page, setPage] = useState(1);
  const [data, loading] = useGetData(
    { url: "https://api.kanye.rest/", params: { page } },
    { cancelable: true }
  );

  if (loading) return <Spinner />;

  const prev = () => setPage(page - 1);
  const next = () => setPage(page + 1);

  return (
    <div>
      <Quote>{data.quote}</Quote>
      <div>
        <Button onClick={prev} disabled={page <= 1} label="← Prev" />
        <span className="mx-5">Page {page}</span>
        <Button onClick={next} disabled={page >= 9} label="Next →" />
      </div>
    </div>
  );
};
Basic TodoMVC CRUD

Edit TodoMVC CRUD

import React from "react";
import axios from "axios";
import {
  provideAxiosInstance,
  useGetData,
  usePostCallback,
  useDeleteCallback,
  usePatchCallback
} from "use-axios-react";

provideAxiosInstance(
  axios.create({
    baseURL: "https://todo-backend-golang-goa.herokuapp.com"
  })
);

/**
 * Map todos to axios request configs
 */
const todoObjectToAxiosRequest = ({ id, title, order, completed }) => ({
  url: id ? `/todos/${id}` : "/todos",
  data: { title, order, completed }
});

const TodoMvcApp = () => {
  // Reusing the same mapping function for all CRUD requests
  const [create, creating, { error: createError }] = usePostCallback(todoObjectToAxiosRequest);
  const [remove, removing, { error: removeError }] = useDeleteCallback(todoObjectToAxiosRequest);
  const [update, updating, { error: updateError }] = usePatchCallback(todoObjectToAxiosRequest);

  // Re-fetch after any of actions is completed
  const allRequestsDone = !creating && !removing && !updating;
  const [todos = [], fetching, { error: fetchError }] = useGetData("/todos", {
    // The hook will re-run every time `depends` changes
    depends: [creating, removing, updating],
    // Actual request will be performed only if this is true
    willRun: allRequestsDone
  });

  if (createError || removeError || updateError || fetchError) {
    return <div>Error occurred, please reload</div>;
  }

  return (
    <Layout>
      <Header loading={creating || removing || updating || fetching}>
        <NewTodo create={create} />
      </Header>
      <TodoList todos={todos} remove={remove} update={update} loading={fetching} />
    </Layout>
  );
};
Common state GET & POST

Edit Common state GET & POST

import React, { useEffect } from "react";
import { useGetData, usePostCallback } from "use-axios-react";

const CreateUser = () => {
  
  // Do an initial load
  const [users = [], loading, { error: loadError, setData: setUsers }] = useGetData("https://reqres.in/api/users");

  // We're particularly interested in the create() callback and the response data (new user data)
  const [create, creating, { error: createError, data: newUser }] = usePostCallback("https://reqres.in/api/users");

  // Update users state evey time the newUser changes
  useEffect(
    () => {
      newUser && setUsers([...users, newUser]);
    },
    [newUser]
  );

  return (
    <Layout>
      <Button onClick={() => create({})}>Create dummy user</Button>

      <span>{(loading || creating) && "Loading..."}</span>
      <span>{(loadError || createError) && "Error occurred"}</span>

      <UserList users={users} />
    </Layout>
  );
};
Using custom axios instance

Edit Using custom axios instance

import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
import { provideAxiosInstance, useGetData } from "use-axios-react";

const customAxiosInstance = axios.create({
  baseURL: "https://reqres.in/api",
  transformResponse: axios.defaults.transformResponse.concat(data => {
    return data.data;
  })
});

provideAxiosInstance(customAxiosInstance);

function App() {
  const [users, loading] = useGetData("/users");

  if (loading) return "Loading...";

  return (
    <div>
      <h1>Users:</h1>
      <code>{JSON.stringify(users)}</code>
    </div>
  );
}

Example apps

API Overview

Hooks

useGetData() Use this one if you need to fetch data depending on some state (e.g. to fetch search results depending on search term)

usePostCallback()

usePutCallback()

usePatchCallback()

useDeleteCallback()

useGetCallback()

Use this if you need to create callbacks to trigger a request programmatically

useParallelPostCallback()

useParallelPutCallback()

useParallelPatchCallback()

useParallelDeleteCallback()

useParallelGetCallback()

Use this if you need to create callbacks to trigger batch requests

Settings

provideAxiosInstance() Provide a custom axios instance to use with the hooks

API Reference


useGetData(url|axiosConfig, options): []

  • url|axiosConfig — Refer to axios request config documentation for details
  • options — The use{...}Data hook options:
cancelable: bool Whether the request should be canceled on component unmount
depends: [] Hook's effect will be re-run only if one of the passed array values changes. Refer to the React useEffect(effect, depends) second argument docs to learn how it works.
willRun: bool Request will be be executed only if this option is true. This is usually an expression such as willRun: !loading
  • result array structure is [data, loading, { error, response, retry, retriesCount, setData }]:

use{Method}Callback(url|axiosConfig|factory, options): []

Where {Method} is one of the following: Post, Put, Patch, Delete, Get

  • url|axiosConfig|factory — Request URL, axios config object or factory, producing an axios config object from callback args
  • result array structure is [exec, loading, { error, retry, response, data, execCount, input }]:

useParallel{Method}Callback(axiosConfigFactory): []

Where {Method} is one of the following: Post, Put, Patch, Delete, Get

  • axiosConfigFactory — A function producing an axios config object from callback args
  • result array structure is [exec, loading, { retry, errors, responses, data, succeed, failed, execCount, input }]
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].