Last active
August 14, 2021 10:49
-
-
Save arghav/e2902c6b903aac0949e1e4642c89baef to your computer and use it in GitHub Desktop.
React context API with Axios
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import axios from 'axios'; | |
import isEqual from 'lodash.isequal'; | |
class Axios extends React.Component { | |
constructor(props) { | |
super(props); | |
// NOTE: Do not use this.context as React uses it internally | |
this.axiosContext = React.createContext(this.value); | |
} | |
axiosRequest() { | |
const { config } = this.props; | |
// Reset the request | |
this.value = null; | |
this.forceUpdate(); | |
axios.request(config).then(response => { | |
this.value = response; | |
this.forceUpdate(); | |
}).catch(error => { | |
this.value = error; | |
this.forceUpdate(); | |
}); | |
} | |
componentDidMount() { | |
this.axiosRequest(); | |
} | |
componentDidUpdate(prevProps) { | |
if (!isEqual(this.props.config, prevProps.config)) { | |
this.axiosRequest(); | |
} | |
} | |
render() { | |
const { | |
children, | |
} = this.props; | |
const { Provider, Consumer } = this.axiosContext; | |
return ( | |
<Provider value={this.value}> | |
<Consumer>{children}</Consumer> | |
</Provider> | |
); | |
} | |
} | |
export default Axios; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as React from 'react'; | |
import Axios from './Axios'; | |
const User = () => ( | |
<Axios | |
config={{ | |
url: "https://api.github.com/users/arghav", | |
headers: { | |
'Accept': 'application/vnd.github.v3+json', | |
}, | |
}} | |
> | |
{response => { | |
if (response instanceof Error) { | |
return <div>{response.message}</div>; | |
} | |
if (response) { | |
return ( | |
<div> | |
<p>{response.data.name}</p> | |
<img src={response.data.avatar_url} width="48px" alt="" /> | |
</div> | |
); | |
} | |
return <div>loading ...</div>; | |
}} | |
</Axios> | |
); | |
export default User; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment