I have two users (admin and user). When I log in as user I display user home screen and when I log out and log in as admin I still see user home screen until I refresh my app, then I can see the admin home screen.
Thank you in advance.
here is my code:
import { auth, db } from '../../firebase';
const Home = ({navigation})=>{
const [modalVisible, setModalVisible]=useState(false)
const [formType, setFormType] = React.useState("")
const [user, setUser] = useState(null) // This user
const [users, setUsers] = useState([]) // Other Users
useEffect(() => {
db.collection("users").doc(auth?.currentUser.uid).get()
.then(user => {
setUser(user.data())
})
}, [])
useEffect(() => {
if (user)
db.collection("users").where("role", "==", (user?.role === "admin" ? 'admin' : null))
.onSnapshot(users => {
if (!users.empty) {
const USERS = []
users.forEach(user => {
USERS.push(user.data())
})
setUsers(USERS)
}
})
}, [user])
const handleSignOut = ()=>{
auth
.signOut()
.then(()=>{
navigation.navigate('SignIn')
})
.catch(error => alert(error.message))
}
return(
<View>
{user?.role === 'admin'? <AdminScreen />:<UserScreen/>}
</View>
)
CodePudding user response:
The issue is that the user state is not being updated when the user logs in as a different account. To solve this issue, I have added a listener to the auth object to detect changes in the current user and updating the user state when the current user changes.
import { auth, db } from '../../firebase';
const Home = ({navigation})=>{
const [modalVisible, setModalVisible]=useState(false)
const [formType, setFormType] = React.useState("")
const [user, setUser] = useState(null) // This user
const [users, setUsers] = useState([]) // Other Users
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(async user => {
if (user) {
const userData = await db.collection("users").doc(user.uid).get();
setUser(userData.data());
} else {
setUser(null);
}
});
return () => unsubscribe();
}, [])
useEffect(() => {
if (user) {
const unsubscribe = db.collection("users").where("role", "==", (user?.role === "admin" ? 'admin' : null))
.onSnapshot(users => {
if (!users.empty) {
const USERS = []
users.forEach(user => {
USERS.push(user.data())
})
setUsers(USERS)
}
});
return () => unsubscribe();
}
}, [user])
const handleSignOut = ()=>{
auth
.signOut()
.then(()=>{
navigation.navigate('SignIn')
})
.catch(error => alert(error.message))
}
return(
<View>
{user?.role === 'admin'? <AdminScreen />:<UserScreen/>}
</View>
)