Search code examples
reactjsuse-effectternary

Ternary operator withing a useEffect() react


I am trying to only fire a useEffect() hook if user does not equal '' (eg. the user is logged on.

Right now I can't get it working - I'd appreciate any advice on how to combine a ternary with useEffect(). Thank!

  const user = useSelector((state) => state.loggedInUser)

  user !== ''
    ? useEffect(() => {
        let data = [user.auth0Id, wallet]
        api
          .updateUserWins(data)
          .then((result) => {
            console.log(result)
            return null
          })
          .catch((err) => {
            console.log(err)
          })
      }, [wallet])
    : console.log('No user')
``

Solution

  • You can't conditionally call a hook. It's stated in the documentation:

    Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns.

    Instead you have to move your conditional operator inside the function you pass to useEffect:

    useEffect(() => {
        if (user !== '') {
            let data = [user.auth0Id, wallet]
            api
              .updateUserWins(data)
              .then((result) => {
                console.log(result)
                return null
              })
              .catch((err) => {
                console.log(err)
              });
        }
        else {
            console.log('No user')
        }
    }, [wallet, user])
    
    

    You may of course use the conditional operator ?: instead of an if if you want to.