I'm trying to reconfigure some Firebase v8 code to firebase v9 in React... On a login/register page, I want to change the online status to true.
I'm not sure if this line of code will be much different or quite literally the same with updated variable names. This may be a very simple question (hopefully). I know in v9 a lot of these types of things are restructured with an import statement of a function already available in the firebase library. IDK if this is one of those things... :/. Thanks for your time! Let me know in advance if I need to include more of the code to make sense...
old (working) v8 code:
variables:
- projectAuth = firebase.auth()
- projectFirestore = firebase.firestore()
focusing on the line just below: "// set online to be true" ...within the login / register page:
try {
// login
const res = await projectAuth.signInWithEmailAndPassword(email, password)
//set online to be true
await projectFirestore.collection('users').doc(res.user.uid)
.update({ online: true })
// dispatch login action
dispatch({ type: 'LOGIN', payload: res.user })
if (!isCancelled) {
setIsPending(false)
setError(null)
}
}
My v9 Code:
variables:
- auth = getAuth()
- db = getFirestore()
try {
// login
await signInWithEmailAndPassword(auth, email, password)
.then((res) => {
// dispatch login action
dispatch({ type: 'LOGIN', payload: res.user })
//set online to be true
await projectFirestore.collection('users').doc(res.user.uid)
.update({ online: true })
if (!isCancelled) {
setIsPending(false)
setError(null)
}
})
CodePudding user response:
There's a top level function updateDoc()
to update documents:
import { updateDoc, doc } from "firebase/firestore";
const docRef = doc(db, "users", res.user.uid)
await updateDoc(docRef, { online: true });