简体   繁体   中英

Trouble with the AuthContext component after using a private route with it

I was following this tutorial regarding Firebase authentication components. Ran into this issue after adding a private route within an Auth Context component: 错误 #1

Console shows other errors alongside this:
#2: 错误 #2

#3: 错误 #3

Auth Context Component:

export const AuthContext = createContext(null);
export const useAuth = () => useContext(AuthContext);

export const AuthProvider = ({ children }) => {
let [currentUser, setCurrentUser] = useState();
const [loadedCredentials, loadingCredentials] = useState(false);

//Other Processes

const loginProcess = (email, password) => {
    return firebase
        .auth()
        .signInWithEmailAndPassword(email, password);
};

//Other Processes

useEffect(() => {
    return firebase.auth().onAuthStateChanged(user => {
        setCurrentUser(user);
        loadingCredentials(true);
    });
}, []);

//Other Processes

return (
    <AuthContext.Provider
        value={ { currentUser, loginProcess } }
        >
        { loadedCredentials && children }
    </AuthContext.Provider>
);}

Private Route Component:

export default function PrivateRoute({ component: Component, ...rest }) {
 
const { currentUser } = useAuth();
return (
    <Route
        {...rest}
        render={props => {
            return currentUser ? <Component {...props} /> : <Redirect to="/login" />
        }}
    ></Route>
);}

The Login Component:

const LogIn = () => {
const [loginStatus, updateStatus] = useState(null);
const { loginProcess } = useAuth();
const history = useHistory();

const loginForm = useFormik({
    //Form values,
    onSubmit: (values) => { loginSubmission(values) }
});

const loginSubmission = (values) => {
    loginProcess(values.email, values.password)
        .then( () => { history.push("/dashboard"); } )
        .catch( (error) => {
            //Error Reporting
        });
};

The App Component:

    const App = () => {
    return (
    <Router>
        <AuthProvider>

        <MainHeader />
        <Switch>

            <Route exact path="/signup">
                    <SignUp />
            </Route>

            <PrivateRoute exact path="/dashboard" component={ <Dashboard /> } />
            //Other Routes

One initial solution that seemed tangentially viable suggested a somewhat different way of writing the exports. Made the change, but it didn't work. Assumed that the error came from use of the useHistory Hook in the Login component, though the train of thought went nowhere when it was put to work. Ran out of options and feel a bit desperate about clearing this problem.

try changing the following line:

<PrivateRoute exact path="/dashboard" component={Dashboard} />

Here is an example of auth context using your code provided:

import { useEffect, useState, createContext } from 'react'
import app from '../utils/firebase'

export const AppContext = createContext()

export const AppProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null)
  const [authState, setAuthState] = useState(false)

  const loginProcess = (email, password) => {
    return app.auth().signInWithEmailAndPassword(email, password)
  }

  useEffect(() => {
    console.log('state unknown')
    setAuthState(false)
    return app.auth().onAuthStateChanged(user => {
      setCurrentUser(user)
      setAuthState(true)
    })
  }, [currentUser])

  return (
    <AppContext.Provider value={{ currentUser, authState, loginProcess }}>
      {authState && children}
    </AppContext.Provider>
  )
}

export const useProvider = () => useContext(AppContext)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM