Can someone explain why I am getting this error in next js? The auth.js
file is also not being run but it used to run before when I import.
ReferenceError: Cannot access ‘AuthProvider’ before initialization
This error happened while generating the page. Any console logs will be displayed in the terminal window.
This is my _app.js
file
import React from "react";
import { AuthProvider } from "contexts/auth";
import { ProtectRoute } from "contexts/auth";
import Nav from "components/Nav";
function MyApp({ Component, pageProps }) {
return (
<AuthProvider>
<Nav />
<ProtectRoute>
<Component {...pageProps} />
</ProtectRoute>
</AuthProvider>
);
}
export default MyApp;
And this is my contexts/auth.js
file
import React, { createContext, useState, useContext, useEffect } from "react";
import Cookies from "js-cookie";
import { fetchWrapper } from "helpers";
const AuthContext = createContext({});
export const AuthProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const loadUserFromCookies = async () => {
// authenticate code
};
loadUserFromCookies();
}, []);
const login = async (email, password) => {
// login code
};
const logout = () => {
// logout code
};
return (
<AuthContext.Provider
value={{ isAuthenticated: !!user, user, login, loading, logout }}
>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);
export const ProtectRoute = ({ children }) => {
const { isAuthenticated, isLoading } = useAuth();
if (
isLoading ||
(!isAuthenticated && window.location.pathname !== "/login")
) {
return () => {
"Loading...";
};
}
return children;
};