1.0.2 • Published 5 years ago

react-safe-http v1.0.2

Weekly downloads
3
License
MIT
Repository
github
Last release
5 years ago

React Safe Http

have you ever get react warning that said Can't perform a React state update on an unmounted component while sending http request and do setState after resolve the request

Example:

class App extends React.Componeent {

    .
    .
    .

    componentDidMount() {
        sendHttpRequest(...)
            .then(res => {
                this.setState({
                    someData: res.data.someData,
                });
            });
    }
    
    .
    .
    .
}

this package will prevent this warning with cancling http request after component has been unmounted.

visit live demo page for see it in action.

instalation

using yarn

yarn add react-safe-http

using npm

npm install --save react-safe-http

withHttp HOC

this higher order component provide http function in your component props.

import {withHttp} from 'react-safe-http';

class App extends React.Componeent {

    .
    .
    .

    componentDidMount() {
        this.props.http({
            method: 'POST',
            url: 'http://...',
            data: {
                foo: bar,
            },
        }).then(res => {
            this.setState({
                someData: res.data.someData,
            });
        });
    }
    
    .
    .
    .
}

export default withHttp(App);

now if your component has been unmounted while http request is fetching, the promise will not resolve and throw an exception.

for catching this error there is an utility function called isCancelError. this function check if catch error is for canceling request or not.

import {withHttp, isCancelError} from 'react-safe-http';

class App extends React.Componeent {

    .
    .
    .

    componentDidMount() {
        this.props.http({
            method: 'POST',
            url: 'http://...',
            data: {
                foo: bar,
            },
        }).then(res => {
            this.setState({
                someData: res.data.someData,
            });
        }).catch(err => {
            if(isCancelError(err)) {
                ...do somthing
            } else {
                ...do somthing else
            }
        });
    }
    
    .
    .
    .
}

export default withHttp(App);

Dependencies

this package uses axios for sending request.

you can call http function like calling axios