I am currently working on an application with firebase initialized on the client side. When a user logs in via firebase, I want to fetch the user's data from the firestore. I am currently doing so within the onAuthStateChanged listener and successfully fetching the user. I am wondering if this is the best way to go about fetching the user data. My code is as follows:
const [currentUser, setCurrentUser] = useState(null)
const [authState, setAuthState] = useState(false)
useEffect(() => {
console.log('state unknown')
setAuthState(false)
auth().onAuthStateChanged(user => {
if (!user) {
return
}
const sourceRef = firestore()
.collection('users')
.where('userId', '==', user.uid)
sourceRef
.get()
.then(snapshot => {
if (snapshot.empty) {
console.log('user not found')
} else {
let data = {}
snapshot.forEach(item => (data = item.data()))
console.log(data)
setCurrentUser(data)
setAuthState(true)
}
})
.catch(error => console.log(error.code))
})
}, [])
return (
<AppContext.Provider value={{ currentUser, authState }}>
{children}
</AppContext.Provider>
)
}
my main concern is that the user's data will be fetched every time the application is refreshed. Any suggestions or best practices on the matter would be greatly appreciated