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

react-axios

v2.0.6

Published

Axios Component for React with child function callback.

Downloads

29,905

Readme

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, makeRequest, axios) => { }
  • 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 ... >
  • Create your own request components wrapped using the withAxios({options})(ComponentToBeWrapped) HoC

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, makeRequest, axios) => {
          if(error) {
            return (<div>Something bad happened: {error.message} <button onClick={() => makeRequest({ params: { reload: true } })}>Retry</button></div>)
          }
          else if(isLoading) {
            return (<div>Loading...</div>)
          }
          else if(response !== null) {
            return (<div>{response.data.message} <button onClick={() => makeRequest({ 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.

makeRequest(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.

axios current instance of axios being used.

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, makeRequest, axios) => {
      ...
    }}
  </Get>
</AxiosProvider>

Or pass down through props

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

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

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

withAxios(Component) HoC

If you need basic access to the axios instance but don't need anything else you can wrap a component using withAxios() higher order component.

const MyComponent = withAxios(class MyComponentRaw 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>
  }
})

withAxios(options)(Component) HoC

If you want to create your own component with the full react-axios request options. You can override the initial options supplied to withAxios at any time by passing options prop to your wrapped component. See below on how this works.

const MyComponent = withAxios({
    url: '/api/user'
    params: {id: "12345"}
  })(class MyComponentRaw extends React.Component {
  render() {
    const {error, response, isLoading, makeRequest, axios} = this.props
    if(error) {
      return (<div>Something bad happened: {error.message}</div>)
    } else if(isLoading) {
      return (<div className="loader"></div>)
    } else if(response !== null) {
      return (<div>{response.data.message}</div>)
    }
    return null
  }
})