When I am trying to change the data – the changes are getting to my Firestore Database, it’s ok, but when I reload the page or logging out and trying to log in again – the user data does not appear in my project, but is also stored in my Firestore Database
. How to save and display user data in the project even after I reload the page?
This is my code
const [email, setEmail] = useState('')
const [phone, setPhone] = useState('')
const [language, setLanguage] = useState('')
const [valute, setValute] = useState('')
const [instagram, setInstagram] = useState('')
const {user} = UserAuth()
const createUser = (email, password) => {
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user;
const uid = user.uid;
setDoc(doc(db, 'users', uid), {
email: email,
name: name,
password: password,
phone: phone,
language: language,
instagram: instagram,
valute: valute,
});
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
// ..
});
}
const updatePerson = async(email, phone, language, valute, instagram, name, ) => {
await updateDoc(doc(db, 'users', user.uid), {email, phone, language, valute, instagram, name})
}
<input type="text" placeholder={name || user.displayName || user.email || user.phoneNumber} className='form-control' onChange={(e) => setName(e.target.value)}/>
<input type="text" placeholder={instagram} className='form-control' onChange={(e) => setInstagram(e.target.value)}/>
<input type="text" placeholder={email} className='form-control' onChange={(e) => setEmail(e.target.value)}/>
<input type="text" placeholder={phone} className='form-control' onChange={(e) => setPhone(e.target.value)}/>
<input type="text" placeholder={language} className='form-control' onChange={(e) => setLanguage(e.target.value)}/>
<input type="text" placeholder={valute} className='form-control' onChange={(e) => setValute(e.target.value)}/>
2
Answers
I've found the answer on my question.
We are expecting that
onSnapshot
will magically be called right after our app loads - it needs some time to fetch document from our collection. I would add additional flag which indicate if data is still loading or not:Then use it like that:
Im using custom hooks for that purpose. That is pretty reusable and i can load multiple (specific) users (or anything else) in same time.
useUserData.jsx
Usage and additional explanations and examples