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-connect

v1.1.6

Published

Simple axios HOC for react components

Downloads

30

Readme

Build Status Coverage Status

HOC for react component to use axios

Simple HOC which provides nice axios features as props.

Install

yarn add axios react-axios-connect

npm i axios react-axios-connect --save

How to use

This hoc pass makeRequest(), isLoading, response and error props to the wrapped component:

{
  error: null | Error, // Axios error if any
  isLoading: boolean,  // whether request is in progress
  makeRequest: (urlOrRequestParams, method = 'get', data = {}, config = {}) => Promise,
  response: Object,    // Axios response object, see https://github.com/axios/axios#response-schema
}

You can also spread the response or specify you own mapping for the props

Very Basic exapmple

  import axiosConnect from 'react-axios-connect';

  class SomeComponent extends React.PureComponent {

    componentDidMount() {
      this.props.makeRequest('/some-api')
    }
    render() {
       const { response: { data }, isLoading, error } = this.props;
       if (isLoading) {
         return '...loading';
       }
       if (error) {
         return 'An error occurred: ' + error;
       }
       return 'Got this data: ' + JSON.stringify(data);
    }
  }

  export default axiosConnect()(SomeComponent);

Availabe params for makeRequest(url, method, data, config)

POST example:

this.props.makeRequest(
  '/some-url',
  'post',
  {data: 'payload', 'for': 'post'}
)

PUT example with additional headers:

const headers = {
  Authorization: 'Bearer some-token'
}

this.props.makeRequest(
  '/some-url',
  'put',
  {data: 'payload', 'for': 'post'},
  { headers }
)

last param config is request config

You can also specify full request config as the only param of makeRequest:

  const requestObj = {
    url: '/some/url',
    method: 'put',
    headers: {
    'Accept': 'json',
    'Authorization': 'Bearer some-oauth2-key'
    }
  }
  this.props.makeRequest(requestObj)

HOC basic options

axiosConnect accepts the list of options to configure component behavior: axiosConnect(options)(SomeComponent);

options is an object which tracks the next keys:

{
    axios: CustomAxiosInstance,
    onMountRequestConfig: RequestConfig, // request config to be used in makeRequest on mount
    initialData: any,        // null by default
    mapping: Function,       // map hoc props to other props `(hocProps: Object): Object => mappedProps`
    spreadResponse: boolean, // false by default, spread the response into data, status, headers e.t.c. props
}

axios key

Pass custom axios instance

onMountRequestConfig key

Request config to be used in call on component mount. This key also can be passed as a prop. If passed both - hoc option & prop, then prop win.

Example:

const onMountRequestConfig = {
  url: '/some-url',
  method: 'post',
  data: { some: 'data' }
}

axiosConnect({ onMountRequestConfig })(Component);

// or

const ConnectedComponent = axiosConnect()(Component);
<ConnectedComponent onMountRequestConfig={ onMountRequestConfig } />

You also can pass a function, it accepts own component props as argument:

const ConnectedComponent = axiosConnect({ onMountRequestConfig: props => {url: props.theUrl })(Component);
<ConnectedComponent theUrl="/some-url" />

In the example above component will load data from /some-url

initialData key

The initial response.data value. At very first load your component won't have any data loaded, so this is useful to not do additional check in your component, i.e. without initialData you'll need to write something like:

  class SomeComponent extends React.PureComponent {
    render() {
      const { response } = this.props;
      if (response.data && response.data.length) {
        // omg we finally got the data, let's render it
        ...
      } else {
        // either, the very first mount or loading
        ...
      }
    }
  }

If you define initial data, then it'll be something like this:

  class SomeComponent extends React.PureComponent {
    render() {
      const { response } = this.props;
      // response.data is always array, as either initialData is an array, or server returns the array
      return response.data.map( .../* render into particualr elements */ );
    }
  }

  axiosConnect({ initialData: [] })(SomeComponent)

spreadResponse key

If true your component will accept reponse props instead of one prop response: data, status, headers, config & request. I.e.:

class SomeComponent extends React.PureComponent {
    render() {
      // no response prop here anymore
      const { data, status } = this.props;
      if (status === 200)
      return <div>{JSON.stringify(data)</div>;
    }
  }

  axiosConnect({ spreadResponse: true })(SomeComponent)

mapping key

You can provide your own mapping hoc props:

  class SomeComponent extends React.PureComponent {
    render() {
      // no 'response' prop here anymore
      const { requestInProgress, serverResponse, requestError } = this.props;
      if (requestInProgress)
        return <div>...loading</div>;
      ...
    }
  }
  const mapping = props => ({
    serverResponse: props.response,
    requestInProgress: props.isLoading,
    requestError: props.error,
    doRequest: props.makeRequest,
  })

  axiosConnect({ mapping })(SomeComponent)

Report an issue / improvement

Feel free to report issue on github.