GithubHelp home page GithubHelp logo

yangzhedi / axios-hooks Goto Github PK

View Code? Open in Web Editor NEW

This project forked from simoneb/axios-hooks

0.0 2.0 0.0 525 KB

๐Ÿฆ† React hooks for axios

License: MIT License

JavaScript 94.56% Shell 5.44%

axios-hooks's Introduction

axios-hooks

Build Status 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://jsonplaceholder.typicode.com/todos/1'
  )
  
  return (
    <div>
      <button onClick={refetch}>refetch</button>
      {loading && <p>Loading...</p>}
      {error && <p>Error!</p>}
      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}
    </div>
  )
}

This example uses the awesome JSONPlaceholder API

Documentation

API

Guides

API

The package exports one default export and named exports:

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

useAxios(url|config)

The main React hook to execute HTTP requests. It accepts the same arguments as axios.

  • url|config The request URL or config object

Returns:

[{ data, loading, error, response }, refetch]

  • 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

  • refetch Function to reload the data

configure({ cache, axios })

Allows to provide custom instances of cache and axios.

serializeCache()

Dumps the request-response cache, to use in server side sendering 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

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

These defaults may not suit your needs:

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

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://jsonplaceholder.typicode.com/'
})

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

configure({ axios, cache })

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'))

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

axios-hooks's People

Contributors

simoneb avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.