Fahad Sohail
Fahad Sohail

Reputation: 1836

ReactJS complex (if / else if) not working as expected

I have the following conditional

if (
    !user.userId
    && match.path === '/login'
) {
    component = <Login/>
} else if (
    user.userId
    && !user.OTPVerified
    && !user.loginWithPassword
    && match.path === '/verify'
) {
    component = <VerifyOTP/>
} else if (
    (user.userId && user.OTPVerified) || (user.userId && user.loginWithPassword)
    && !user.profileCompleted
    && match.path === '/complete-profile'
) {
    console.log('userid', user.userId)
    console.log('otpverified', user.OTPVerified)
    console.log('loginWithPassword', user.loginWithPassword)
    console.log('profileCompleted', user.profileCompleted)
    console.log('path', match.path)
    component = <CompleteProfile/>
} else if (
    user.userId
    && !user.OTPVerified
    && user.loginWithPassword
    && user.profileCompleted
    && match.path === '/login-password'
) {
    component = <LoginWithPassword/>
} else {
    component = <Login/>
}

console returns

userid 29
otpverified true
loginWithPassword false
profileCompleted true
path /login

I dont get why am i still seeing CompleteProfile component

Upvotes: 0

Views: 34

Answers (1)

Todd Skelton
Todd Skelton

Reputation: 7239

Add some parenthesis around those two expressions with the || between them if they should be evaluated together.

((user.userId && user.OTPVerified) || (user.userId && user.loginWithPassword))

This change makes your Login component show based on the values.

You can remove the inner ones too and the && will be evaluated first.

(user.userId && user.OTPVerified || user.userId && user.loginWithPassword)

else if (
    (user.userId && user.OTPVerified || user.userId && user.loginWithPassword)
    && !user.profileCompleted
    && match.path === '/complete-profile'
)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND#Operator_precedence

console.log((true && true) || (true && false) && false && false) //true
console.log((true && true || true && false) && false && false) // false

Upvotes: 1

Related Questions