I have an app that allows a user to register for an account and then do various things once they have logged in. Once they have logged in , one of the things they can do is create a todo list. I want this todo list to be able to be recalled by the user later on, but I can't figure out how to save it to the database with the specific user who is logged in. I am 100% noob with firebase/react. So far I can get the list to save to a totally new document in the cloud database, but not update the with a specific user.
Thanks!
CodePudding user response:
- Check if the user is logged in
Docs for that https://firebase.google.com/docs/auth/web/manage-users
const user = firebase.auth().currentUser
if (user) {
// User is logged in
} else {
// No user logged in
}
Read the todo, I guess it would a state of a component
Write the state to firebase, if would prefer firestore. This all will be inside the
if(user)
https://firebase.google.com/docs/firestore/manage-data/add-data#web-version-9
import { doc, setDoc } from "firebase/firestore";
const docRef = doc(db, 'todoList', uid);
setDoc(cityRef, { todoList: todoListState }, { merge: true });
CodePudding user response:
I hope you are using firestore as the database in firebase. Firestore saves all the information as JSON Tree with the hierarchy of Collection-document which means you can have multiple document inside a collection and once again each document can have multiple collection in them.
To save the TODO information in the Firestore first you need to think how you are going to structure your collection and document for the whole application. This structure will also depend on how to secure the data for each user.
Following is an example of the structure you could have for the database for TODO list
/users/{firebaseUID}/todolist/mylist
in the above structure users and todolist are collection and firebaseUID and mylist are document names. I have given the firebaseUID inside the curly braces because it will be different for each user
To add or update the list for each of the users you will pass the following information
const myListData = // Something
const userId = // ger the data from firebase.auth().currentUser.uid or other options
// hope you know how to get the object of firestore from React Firestore package
// Create
Firestore.doc(`/users/${userId}/todolist/mylist`).create(myListData);
//Update
Firestore.doc(`/users/${userId}/todolist/mylist`).update(myListData);
CodePudding user response:
Create a new key in your database with the uid of the user and push the list there. For example:
db.ref('/users').child(`${user.uid}`).set({list: theList})