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-axios-react

v0.2.3

Published

Axios in React in the hooks era

Downloads

224

Readme

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>
  );
};

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>
  );
};

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>
  );
};

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>
  );
};

Example apps

API Overview

Hooks

Settings

API Reference


useGetData(url|axiosConfig, options): []

  • url|axiosConfig — Refer to axios request config documentation for details
  • options — The use{...}Data hook options:
  • 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 }]

Support 👩‍

  • Please feel free to create issues with questions