Skip to content

Instantly share code, notes, and snippets.

@Yougigun
Created July 29, 2020 13:40
Show Gist options
  • Save Yougigun/665c7a9ff2893a12d87db7c7b38a33f4 to your computer and use it in GitHub Desktop.
Save Yougigun/665c7a9ff2893a12d87db7c7b38a33f4 to your computer and use it in GitHub Desktop.
Handle Request and Response Error
import React, {useEffect,useState}from 'react';
import Modal from '../../components/UI/Modal/Modal'
import Aux from '../Auxiliary/Auxiliary'
const withErrorHandler = (WrappedComponent,axios) => {
return (props)=>{
const [state, setstate] = useState({error:null})
// useEffect(() => {
// axios.interceptors.request.use(req=>{
// setstate({error:null})
// return req
// })
// axios.interceptors.response.use(res=>res, error=>{
// setstate({error:error})
// return Promise.reject(error)
// } )
// }, [])
const errorConfirmHandler = ()=>{
setstate({error:null})
}
const reqInterceptor = axios.interceptors.request.use(req=>{
setstate({error:null})
return req
},
error => Promise.reject(error)
)
const resInterceptor = axios.interceptors.response.use(res=>res,
error=>{
// console.log(error)
setstate({error:error})
return Promise.reject(error)
} )
useEffect(()=>{
console.log("withErrorHandler - mount")
return ()=>{
console.log('withErrorHandler - clean up',reqInterceptor,resInterceptor)
axios.interceptors.request.eject(reqInterceptor)
axios.interceptors.request.eject(resInterceptor)
}
},[])
return(
<Aux>
<Modal
show = {state.error}
modalClosed={errorConfirmHandler}
>{state.error?state.error.message:null}</Modal>
<WrappedComponent {...props} />
</Aux>
)
}
}
export default withErrorHandler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment