-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherrorHandler.js
More file actions
41 lines (33 loc) · 1001 Bytes
/
errorHandler.js
File metadata and controls
41 lines (33 loc) · 1001 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import React from "react";
import { useState, useEffect } from "react";
import { useMemo } from "react";
import { useContext } from "react";
import Error404 from "../pages/404";
import Router from "next/router";
const ErrorStatusContext = React.createContext();
const ErrorHandler = ({ children }) => {
const [errorStatusCode, setErrorStatusCode] = useState(undefined);
useEffect(() => {
Router.events.on("routeChangeComplete", () =>
setErrorStatusCode(undefined)
);
}, []);
const renderContent = () => {
if (errorStatusCode === 404) {
return <Error404 />;
}
// ... more HTTP codes handled here
return children;
};
const contextPayload = useMemo(
() => ({ setErrorStatusCode }),
[setErrorStatusCode]
);
return (
<ErrorStatusContext.Provider value={contextPayload}>
{renderContent()}
</ErrorStatusContext.Provider>
);
};
export const useErrorStatus = () => useContext(ErrorStatusContext);
export default ErrorHandler;