As a beginner in react and javascript, I am facing an issue with showing an ActivityIndicator while logging in a user. The setIsLoading method doesn't seem to change the state and trigger a rerender. When the handleLogin method is called on a button click, useEffect isn't being executed as expected, as it's not printed to the console. Additionally, despite setting isLoading to true, console.log(isLoading) still displays false. Interestingly, when I commented out the firebase section, everything worked fine. If anyone can shed light on this behavior, I would greatly appreciate it. Thank you.
import React, { useState, useEffect } from 'react'
import firebase from '../firebase'
import { ActivityIndicator, StyleSheet, Text, TextInput, View, Button} from 'react-native'
export default function LoginScreen({navigation}) {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [errorMessage, setErrorMessage] = useState(null)
const [isLoading, setIsLoading] = useState(false)
const [showLoader, setShowLoader] = useState(false)
useEffect(() => {
setShowLoader(isLoading)
console.log('useEffect')
},[isLoading])
const handleLogin = () => {
setIsLoading(true)
console.log(isLoading)
firebase.auth().signInWithEmailAndPassword(email, password)
.then(() => { navigation.navigate('Home')})
.then(setIsLoading(false))
.catch((error) => {setErrorMessage(error.message)})
console.log('handleLogin')
}
return (
<View style={styles.container}>
<Text>Login</Text>
{errorMessage &&
<Text style={{ color: 'red' }}>
{errorMessage}
</Text>}
<TextInput
style={styles.textInput}
autoCapitalize="none"
placeholder="Email"
onChangeText={email => setEmail(email)}
value={email}
/>
<TextInput
secureTextEntry
style={styles.textInput}
autoCapitalize="none"
placeholder="Password"
onChangeText={password => setPassword(password)}
value={password}
/>
<Button title="Login" onPress={handleLogin} />
<Button
title="Don't have an account? Sign Up"
onPress={() => navigation.navigate('SignUp')}
/>
{
showLoader && <ActivityIndicator/>
}
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
textInput: {
height: 40,
width: '90%',
borderColor: 'gray',
borderWidth: 1,
marginTop: 8
}
})
Edit: After some exploration, I realized that the useEffect is only triggered after the handleLogin method completes its execution. This means that isLoading is set to true but then reverted back to false after the signin process, rendering the useEffect ineffective. Any suggestions or insights on how to resolve this sequence of events would be highly appreciated. Thank you!