Created
July 29, 2020 13:40
-
-
Save Yougigun/665c7a9ff2893a12d87db7c7b38a33f4 to your computer and use it in GitHub Desktop.
Handle Request and Response Error
This file contains 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 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