I want to make HOC with axios handler so i don't need to handling all possible feedback from response (404,200,401, response, etc)
here's my withFetchingAxios
:
export default (Component)=> class extends React.PureComponent{
constructor(props) {
super(props);
this.state = {
response:null,
error:'',
isLoading:false
};
this.makeRequest = this.makeRequest.bind(this);
}
async makeRequest({method='get', url, data=null, config=null}){
console.log(method , url, data, config)
try {
this.setState({isLoading:true})
AxiosInstance[method](url, JSON.parse(config), JSON.parse(data))
.then((res) => {
this.setState({response:res.data})
})
.catch((err) => {
this.setState({error:err})
})
.finally(() => {
this.setState({isLoading:false})
});
} catch (err) {
console.log('err withFetchingAxios' , err)
this.setState({error:err, isLoading:false})
}
}
render(){
if(this.state.isLoading){
return(
//show loader component
)
} // else if error show component error,
return(
<Component
{...this.props}
response={this.state.response}
makeRequest={({method='get', url, data, config})=>this.makeRequest({method, url, data, config})}
/>
)
}
}
and i just used it in my other component like Home
:
export default withFetchingAxios(class Home extends React.Component{
/**
* List function to handling component
*/
componentDidMount(){
this.props.makeRequest({url:'posts'})
}
/**
* List function to render component
*/
/**
* End list function to render component
*/
render() {
return(
//Home UI
)
}
})
but i got infinite loop from console.log
in async makeRequest()
function in HOC,
how do i avoid it and just let HOC call makeRequest()
once?
i need to handle HOC to have an ability
like:
- Call HOC when didmount if
axios
method isget
- Call HOC from
onPress
event if method ispost