Skip to content

Instantly share code, notes, and snippets.

@chunkzer
Created August 9, 2020 04:18
Show Gist options
  • Select an option

  • Save chunkzer/e0b37452ac65501b9b28534b9419ffdd to your computer and use it in GitHub Desktop.

Select an option

Save chunkzer/e0b37452ac65501b9b28534b9419ffdd to your computer and use it in GitHub Desktop.
/**
* @example A hook for setting Error Messages
* import 'hooks/useError';
*
* @param {String} defaultErrorMessage
*/
export default (defaultErrors = []) => {
const [errors, setError] = useState(defaultErrors);
const raiseError = message => setError([...errors, message]);
const dismissError = index => {
const preceedingErrors = errors.slice(0, index);
const proceedingErrors = errors.slice(index + 1, errors.length);
setError([...preceedingErrors, ...proceedingErrors]);
};
return [errors, raiseError, dismissError];
};
//
import useErrors from '../hooks/useErrors';
const ErrorContext = React.createContext([[], () => {}, () => {}]);
const ErrorProvider = ({ children }) => {
const hardCodedErrors = ['Oh no!', 'Something bad...', ' : ( '];
const [errorMessages, , dismissError] = useErrors(hardCodedErrors);
return (
<ErrorContext.Provider value={[errorMessages, (message) => console.error(message), dismissError]}>
{children}
</ErrorContext.Provider>
);
};
export { ErrorContext, ErrorProvider };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment