简体   繁体   中英

How can I use a hook after conditional statements in React?

I have this following code using the react firebase hooks library :

    // load user state 
    const [user, loadingAuthState, errorAuthState] = useAuthState(auth);

    // user is loading...
    if(loadingAuthState)
    {
      return <div>טוען...</div>
    }
    // an error has occured
    else if(errorAuthState)
    {
      alert(errorAuthState);
      return <Redirect to="login"/>
    }
    // if the user is not set, return to the login page
    else if(!(user))
    {
      return (<Redirect to="/login"/>)
    }

    // load data from the user using the user's ID.
    const [value, loading, error] = useDocumentData(doc(db, "users", user.uid));

I get this error:

Line 46:37: React Hook "useDocumentData" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return? react-hooks/rules-of-hooks

I understand the idea of calling hooks at the top level, however, I need to know the user's ID before using the 2nd hook to read data, so how can I structure my code in a way that doesn't conflict with React's guidelines? I'd like to keep the "loading" message that is returning while the user is loading.

One way of doing it is to split this code into two components so that you return another component when you know the user's ID. Inside of this second component you can have useDocumentData hook unconditionally because you would already know the user's ID passed in through props.

    // load user state 
    const [user, loadingAuthState, errorAuthState] = useAuthState(auth);

    // user is loading...
    if(loadingAuthState)
    {
      return <div>טוען...</div>
    }
    // an error has occured
    else if(errorAuthState)
    {
      alert(errorAuthState);
      return <Redirect to="login"/>
    }
    // if the user is not set, return to the login page
    else if(!(user))
    {
      return (<Redirect to="/login"/>)
    }

    // load data from the user using the user's ID.
    return <MyComponentWithUserId userId={user.uid} />

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