how to use logical operator && in try and catch react native

65 Views Asked by At

I want to perform an action if and only if the user details have been fetched but they are fetched after the token and the logical operator && is running even if the condition is false and user details are not there

try {
        await axios.post(`${BASE_URL}/api/moralis/login`,
            {
                userObjectId: id,
                sessionToken: sessionToken
            })
            .then((resp) =>
                AsyncStorage.setItem('token', resp.data.user.token),
                AuthStore.setToken()))

        {
            Object.keys(UserStore.state.user).length &&
                (
                    console.log('run===>', Boolean(Object.keys(UserStore.state.user).length)),
                    navigation(),
                    setLoading(false))
        }


    } catch (error) {
        Errored(error)
        setLoading(false)
    }
1

There are 1 best solutions below

0
Erfin Badriansyah On

I don't know what other parameter do you want to check but i feel you want something like this?

try {
    const _req = await axios.post(`${BASE_URL}/api/moralis/login`,{
            userObjectId: id,
            sessionToken: sessionToken
    })
    if(_req.data.user.token){
        AsyncStorage.setItem('token', resp.data.user.token)
        AuthStore.setToken()
    }
    if(Object.keys(UserStore.state.user).length && true){ //just change second arg with yours
        console.log('run===>', Boolean(Object.keys(UserStore.state.user).length))
        navigation()
        setLoading(false)
    }
} catch (error) {
    Errored(error)
    setLoading(false)
}

or with callback function

try {
    await axios.post(`${BASE_URL}/api/moralis/login`,{
            userObjectId: id,
            sessionToken: sessionToken
    }).then((resp)=>{
        if(resp.data.user.token){
            AsyncStorage.setItem('token', resp.data.user.token)
            AuthStore.setToken()
        }
        if(Object.keys(UserStore.state.user).length && true){ //just change second arg with yours
            console.log('run===>', Boolean(Object.keys(UserStore.state.user).length))
            navigation()
            setLoading(false)
        }
    })
    
} catch (error) {
    Errored(error)
    setLoading(false)
}