Git Product home page Git Product logo

react-axios's Introduction

npm Build Status npm npm

react-axios

Axios Component for React with child function callback. This is intended to allow in render async requests.

Features

  • Same great features found in Axios
  • Component driven
  • Child function callback (error, response, isLoading, onReload) => { }
  • Auto cancel previous requests
  • Debounce to prevent rapid calls.
  • Request only invoked on prop change and isReady state.
  • Callback props for onSuccess, onError, and onLoading
  • Supports custom axios instances through props or a <AxiosProvider ... >

Installing

Using npm:

$ npm install react-axios

Also install the required peer dependancies if you have not already done so:

$ npm install axios
$ npm install react
$ npm install prop-types

Components & Properties

Base Request Component

<Request
  instance={axios.create({})} /* custom instance of axios - optional */
  method="" /* get, delete, head, post, put and patch - required */
  url="" /*  url endpoint to be requested - required */
  data={} /* post data - optional */
  params={} /* queryString data - optional */
  config={} /* axios config - optional */
  debounce={200} /* minimum time between requests events - optional */
  debounceImmediate={true} /* make the request on the beginning or trailing end of debounce - optional */
  isReady={true} /* can make the axios request - optional */
  onSuccess={(response)=>{}} /* called on success of axios request - optional */
  onLoading={()=>{}} /* called on start of axios request - optional */
  onError=(error)=>{} /* called on error of axios request - optional */
/>

Helper Components

<Get ... />
<Delete ... />
<Head ... />
<Post ... />
<Put ... />
<Patch ... />

Example

Include in your file

import { AxiosProvider, Request, Get, Delete, Head, Post, Put, Patch, withAxios } from 'react-axios'

Performing a GET request

// Post a request for a user with a given ID
render() {
  return (
    <div>
      <Get url="/api/user" params={{id: "12345"}}>
        {(error, response, isLoading, onReload) => {
          if(error) {
            return (<div>Something bad happened: {error.message} <button onClick={() => onReload({ params: { reload: true } })}>Retry</button></div>)
          }
          else if(isLoading) {
            return (<div>Loading...</div>)
          }
          else if(response !== null) {
            return (<div>{response.data.message} <button onClick={() => onReload({ params: { refresh: true } })}>Refresh</button></div>)
          }
          return (<div>Default message before request is made.</div>)
        }}
      </Get>
    </div>
  )
}

Exposed properties on the child function.

error The error object returned by Axios.

response The response object returned by Axios.

isLoading Boolean flag indicating if Axios is currently making a XHR request.

onReload(props) Function to invoke another XHR request. This function accepts new temporary props that will be overloaded with the existing props for this request only.

Custom Axios Instance

Create an axios instance

const axiosInstance = axios.create({
  baseURL: '/api/',
  timeout: 2000,
  headers: { 'X-Custom-Header': 'foobar' }
});

Pass down through a provider

<AxiosProvider instance={axiosInstance}>
  <Get url="test">
    {(error, response, isLoading, onReload) => {
      ...
    }}
  </Get>
</AxiosProvider>

Or pass down through props

<Get url="test" instance={axiosInstance}>
  {(error, response, isLoading, onReload) => {
    ...
  }}
</Get>

Retrieve from custom provider (when you need to directly use axios). The default instance will be passed if not inside an <AxiosProvider/>.

const MyComponent = withAxios(class MyComponentImpl extends React.Component {
  componentWillMount() {
    this.props.axios('test').then(result => {
      this.setState({ data: result.data })
    })
  }
  render() {
    const data = (this.state || {}).data
    return <div>{JSON.stringify(data)}</div>
  }
})

<AxiosProvider instance={axiosInstance}>
  <MyComponent/>
</AxiosProvider>

react-axios's People

Contributors

binki avatar gotoplanb avatar jakedahm avatar roprgm avatar sheaivey 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.