0.0.1 • Published 2 years ago
react-hooks-use-error v0.0.1
React Hook to provide more feature when work with errors.
Install
yarn add react-hooks-use-error
or
npm i -S react-hooks-use-error
Usage
Simple example:
import { useError } from 'react-hooks-use-error'
function MyComponent() {
const errorState = useError()
const { error, isErrored, setError, resetError } = errorState
async function fetchData() {
try {
await api.fetchSomething()
} catch (e) {
setError(e)
}
}
useEffect(() => {
fetchData()
}, [])
return <div>{error}</div>
}
ErrorMessageProvider
You can set error processor in global context. It is good when you have same api or same errors in many components, or you want to support localization.
import { ErrorMessageProvider } from 'react-hooks-use-error'
function ComponentWithErrorMessageProvider({ user_id }) {
const getErrorMessage = (e) => {
// axios api error example
const { status, data } = e.request || {}
const { errorCode } = data
if(errorCode === 'email-is-invalid') {
return 'Email you provided is invalid. Try to use different email'
}
return e.message
}
return (
<ErrorMessageProvider getErrorMessage={getErrorMessage}>
<App />
</ErrorMessageProvider>
)
}
See Also
List of libraries that work well with hook:
0.0.1
2 years ago
0.0.0-rc.1
2 years ago