All Projects → simoneb → Axios Hooks

simoneb / Axios Hooks

Licence: mit
🦆 React hooks for axios

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Axios Hooks

Vue Cnode
🚀 基于vue3 function-based 构建cnode社区
Stars: ✭ 192 (-77.73%)
Mutual labels:  hooks, axios
React Ufo
🛸 react-ufo - A simple React hook to help you with data fetching 🛸
Stars: ✭ 85 (-90.14%)
Mutual labels:  hooks, axios
react-movies-finder
React Movies finder is a React app to search movies and series using redux, redux-thunk, React Hooks, and Material UI
Stars: ✭ 27 (-96.87%)
Mutual labels:  hooks, axios
Spotify Clone Client
A ReactJS clone application of the popular Spotify music streaming service. This application utilizes the Spotify API and the Spotify Web Playback SDK
Stars: ✭ 162 (-81.21%)
Mutual labels:  hooks, axios
Vue Cli
📃基于 Vue3.0 Composition Api 快速构建实战项目
Stars: ✭ 335 (-61.14%)
Mutual labels:  hooks, axios
Vue2 Study
vue 的webpack配置,按需加载,element-ui,vuex
Stars: ✭ 16 (-98.14%)
Mutual labels:  axios
Cykspace Node
博客后台服务~~ 👉👉 http://www.cykspace.com
Stars: ✭ 23 (-97.33%)
Mutual labels:  axios
React Latest Framework
a client framework of React
Stars: ✭ 835 (-3.13%)
Mutual labels:  hooks
Web3 React
🧰 A simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps
Stars: ✭ 788 (-8.58%)
Mutual labels:  hooks
Vue Qq
🎨 Vue family bucket with socket.io and express/koa2 , create a web version of mobile QQ, supporting real-time group chat, real-time private chat, special care, shielding chat, smart IP geographic location, real-time display temperature and other QQ core functions
Stars: ✭ 861 (-0.12%)
Mutual labels:  axios
Vue Stack
Minimalistic Boilerplate for FullStack Express and Vue.js applications
Stars: ✭ 26 (-96.98%)
Mutual labels:  axios
Usestatewithlayoutanimation
Abstraction for `React Native`'s `LayoutAnimation` and `useState`
Stars: ✭ 19 (-97.8%)
Mutual labels:  hooks
Swagger Axios Converter
swagger axios converter
Stars: ✭ 16 (-98.14%)
Mutual labels:  axios
Flagchecker
For effective cheating detection in competitions. Utilizes Linux Kernel Module (LKM) for generating flags.
Stars: ✭ 24 (-97.22%)
Mutual labels:  hooks
Fuse
A simple file sharing web service in Vue.js and Flask
Stars: ✭ 7 (-99.19%)
Mutual labels:  axios
Vue Music
基于vue2.0的网易云音乐播放器,api来自于NeteaseCloudMusicApi,v2.0为最新版本
Stars: ✭ 855 (-0.81%)
Mutual labels:  axios
Vuejs Training
VueJS training including Vue ecosystem: HTTP (Axios), Vuex, Unit Testting (Jest)...
Stars: ✭ 6 (-99.3%)
Mutual labels:  axios
Redux Axios Middleware
Redux middleware for fetching data with axios HTTP client
Stars: ✭ 902 (+4.64%)
Mutual labels:  axios
Genesis Simple Hook Guide
WordPress plugin that displays names of all Genesis hooks on the current page dynamically.
Stars: ✭ 25 (-97.1%)
Mutual labels:  hooks
Jdf Phone Ui
🖖 前端混合开发整合框架(cordova插件,微信,H5)
Stars: ✭ 18 (-97.91%)
Mutual labels:  axios

axios-hooks

Node.js CI codecov npm version bundlephobia

React hooks for axios, with built-in support for server side rendering.

Features

  • All the axios awesomeness you are familiar with
  • Zero configuration, but configurable if needed
  • One-line usage
  • Super straightforward to use with SSR

Installation

npm install axios axios-hooks

axios is a peer dependency and needs to be installed explicitly

Quick Start

Edit axios-hooks Quick Start

import useAxios from 'axios-hooks'

function App() {
  const [{ data, loading, error }, refetch] = useAxios(
    'https://reqres.in/api/users?delay=1'
  )

  if (loading) return <p>Loading...</p>
  if (error) return <p>Error!</p>

  return (
    <div>
      <button onClick={refetch}>refetch</button>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  )
}

Documentation

API

Examples

Guides

API

The package exports one default export and named exports:

import useAxios, { configure, loadCache, serializeCache } from 'axios-hooks'

useAxios(url|config, options)

The main React hook to execute HTTP requests.

  • url|config - The request URL or config object, the same argument accepted by axios.
  • options - An options object.
    • manual ( false ) - If true, the request is not executed immediately. Useful for non-GET requests that should not be executed when the component renders. Use the execute function returned when invoking the hook to execute the request manually.
    • useCache ( true ) - Allows caching to be enabled/disabled for the hook. It doesn't affect the execute function returned by the hook.
    • ssr ( true ) - Enables or disables SSR support

Returns

[{ data, loading, error, response }, execute, manualCancel]

  • data - The success response data property (for convenient access).

  • loading - True if the request is in progress, otherwise False.

  • error - The error value

  • response - The whole success response object.

  • execute([config[, options]]) - A function to execute the request manually, bypassing the cache by default.

    • config - Same config object as axios, which is shallow-merged with the config object provided when invoking the hook. Useful to provide arguments to non-GET requests.
    • options - An options object.
      • useCache ( false ) - Allows caching to be enabled/disabled for this "execute" function.
  • manualCancel() - A function to cancel outstanding requests manually.

    Returns

    A promise containing the response. If the request is unsuccessful, an exception is thrown and must be handled manually.

configure({ cache, axios, defaultOptions })

Allows to provide custom instances of cache and axios and to override the default options.

  • cache An instance of lru-cache, or false to disable the cache
  • axios An instance of axios
  • defaultOptions An object overriding the default Hook options. It will be merged with the default options.

serializeCache()

Dumps the request-response cache, to use in server side rendering scenarios.

Returns

Promise<Array> A serializable representation of the request-response cache ready to be used by loadCache

loadCache(cache)

Populates the cache with serialized data generated by serializeCache.

  • cache The serializable representation of the request-response cache generated by serializeCache

makeUseAxios({ cache, axios, defaultOptions })

Creates an instance of the useAxios hook configured with the supplied cache, axios instance and default options.

  • cache An instance of lru-cache, or false to disable the cache
  • axios An instance of axios
  • defaultOptions An object overriding the default Hook options. It will be merged with the default options.

Returns

An instance of useAxios React Hook which will always use the provided cache and axios instance.

The returned value, besides being a function that can be used as a React Hook, also contains the properties:

  • resetConfigure
  • configure
  • loadCache
  • serializeCache

which are the same as the package's named exports but limited to the useAxios instance returned by makeUseAxios.

Configuration

Unless provided via the configure function, axios-hooks uses as defaults:

  • axios - the default axios package export
  • cache - a new instance of the default lru-cache package export, with no arguments
  • defaultOptions - { manual: false, useCache: true, ssr: true }

These defaults may not suit your needs, for example:

  • you may want a common base url for axios requests
  • the default (Infinite) cache size may not be a sensible default
  • you want to disable caching altogether

In such cases you can use the configure function to provide your custom implementation of both.

When configure is used, it should be invoked once before any usages of the useAxios hook

Example

Edit axios-hooks configuration example

import { configure } from 'axios-hooks'
import LRU from 'lru-cache'
import Axios from 'axios'

const axios = Axios.create({
  baseURL: 'https://reqres.in/api'
})

const cache = new LRU({ max: 10 })

configure({ axios, cache })

Manual Requests

On the client, requests are executed when the component renders using a React useEffect hook.

This may be undesirable, as in the case of non-GET requests. By using the manual option you can skip the automatic execution of requests and use the return value of the hook to execute them manually, optionally providing configuration overrides to axios.

Example

In the example below we use the useAxios hook twice. Once to load the data when the component renders, and once to submit data updates via a PUT request configured via the manual option.

Edit axios-hooks Manual Request

import useAxios from 'axios-hooks'

function App() {
  const [{ data: getData, loading: getLoading, error: getError }] = useAxios(
    'https://reqres.in/api/users/1'
  )

  const [
    { data: putData, loading: putLoading, error: putError },
    executePut
  ] = useAxios(
    {
      url: 'https://reqres.in/api/users/1',
      method: 'PUT'
    },
    { manual: true }
  )

  function updateData() {
    executePut({
      data: {
        ...getData,
        updatedAt: new Date().toISOString()
      }
    })
  }

  if (getLoading || putLoading) return <p>Loading...</p>
  if (getError || putError) return <p>Error!</p>

  return (
    <div>
      <button onClick={updateData}>update data</button>
      <pre>{JSON.stringify(putData || getData, null, 2)}</pre>
    </div>
  )
}

Manual Cancellation

The cancellation method can be used to cancel an outstanding request whether it be from the automatic hook request or from the manual execute method.

Example

In the example below we use the useAxios hook with its automatic and manual requests. We can call the cancellation programmatically or via controls.

function App() {
  const [pagination, setPagination] = useState({});
  const [{ data, loading }, refetch, cancelRequest] = useAxios({
    url: "/users?delay=5",
    params: { ...pagination }
  });

  const handleFetch = () => {
    setPagination({ per_page: 2, page: 2 });
  };

  const externalRefetch = async () => {
    try {
      await refetch();
    } catch(e) {
      // Handle cancellation
    }
  };

  return (
    <div>
      <button onClick={handleFetch}>refetch</button>
      <button onClick={externalRefetch}>External Refetch</button>
      <button disabled={!loading} onClick={cancelRequest}>Cancel Request</button>
      {loading && <p>...loading</p>}
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

Server Side Rendering

axios-hooks seamlessly supports server side rendering scenarios, by preloading data on the server and providing the data to the client, so that the client doesn't need to reload it.

How it works

  1. the React component tree is rendered on the server
  2. useAxios HTTP requests are executed on the server
  3. the server code awaits serializeCache() in order to obtain a serializable representation of the request-response cache
  4. the server injects a JSON-serialized version of the cache in a window global variable
  5. the client hydrates the cache from the global variable before rendering the application using loadCache

Example

Edit axios-hooks SSR example

<!-- fragment of the HTML template defining the window global variable -->

<script>
  window.__AXIOS_HOOKS_CACHE__ = {{{cache}}}
</script>
// server code for the server side rendering handler

import { serializeCache } from 'axios-hooks'

router.use(async (req, res) => {
  const index = fs.readFileSync(`${publicFolder}/index.html`, 'utf8')
  const html = ReactDOM.renderToString(<App />)

  // wait for axios-hooks HTTP requests to complete
  const cache = await serializeCache()

  res.send(
    index
      .replace('{{{html}}}', html)
      .replace('{{{cache}}}', JSON.stringify(cache).replace(/</g, '\\u003c'))
  )
})
// client side code for the application entry-point

import { loadCache } from 'axios-hooks'

loadCache(window.__AXIOS_HOOKS_CACHE__)

delete window.__AXIOS_HOOKS_CACHE__

ReactDOM.hydrate(<App />, document.getElementById('root'))

Multiple Hook Instances

Sometimes it is necessary to communicate with different APIs or use different caching strategies for different HTTP interactions.

makeUseAxios allows to create multiple instances of the useAxios React Hook which can be configured and managed independently.

In other words, makeUseAxios is a factory of useAxios, which returns a React Hook configured against the provided axios or cache instances.

This feature can also be used to create a single pre configured React Hook instance as an alternative to the global configure feature

Example

Edit axios-hooks makeUseAxios

import axios from 'axios'
import { makeUseAxios } from 'axios-hooks'

const useAxios = makeUseAxios({
  axios: axios.create({ baseURL: 'https://reqres.in/api' })
})

function App() {
  const [{ data, loading, error }, refetch] = useAxios('/users?delay=1')

  if (loading) return <p>Loading...</p>
  if (error) return <p>Error!</p>

  return (
    <div>
      <button onClick={refetch}>refetch</button>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  )
}

Promises

axios-hooks depends on a native ES6 Promise implementation to be supported. If your environment doesn't support ES6 Promises, you can polyfill.

Credits

axios-hooks is heavily inspired by graphql-hooks, developed by the awesome people at NearForm.

License

MIT

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].