Reputation: 163
I am new to firebase / firestore and am trying to create a new collection upon login and authenticating a user, on client side and using React. I read a few other articles here and I set the db rules to true for both read and write, but yet, I keep getting an error on the Firestore db, while it works perfectly if I initialise a Realtime Database. Also, I can get and read data, but not write it.
The code I have is pretty simple:
export default function Login() {
const [isAuthenticated, setAuthenticate] = useState(false);
const [newEditor, setNewEditor] = useState("");
const uiConfig = {
signInFlow: "popup",
signInOptions: [firebase.auth.GoogleAuthProvider.PROVIDER_ID],
callbacks: {
signInSuccessWithAuthResult: (user) => {
console.log("success");
createUserRoles(newEditor);
},
},
};
useEffect(() => {
firebase.auth().onAuthStateChanged((user) => {
if (user) {
if (user.email.split("@")[1] === "something.com") {
setAuthenticate(!!user);
setNewEditor(user.email);
console.log(newEditor);
} else {
console.log("not allowed");
}
}
});
});
const createUserRoles = (user) => {
//on login the user will be added to editors collection with default value of reviewer
console.log("hello from createeee");
const editorsRef = firebase.database().ref("editors");
const editor = {
email: "user.email",
role: "reviewer",
lastSession: Date.now(),
};
editorsRef.push(editor);
};
return (
.....
and my rules are set as such:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read: if true;
allow write: if true;
}
}
}
Does anyone have an idea of how I can do this?
Upvotes: 1
Views: 37
Reputation: 5840
First off, double check that you're including the Firestore SDK in your code. Then...you're using RTDB syntax to try to add a document to Firestore in createUserRoles
. You need to switch it to Firestore's syntax:
const createUserRoles = async (user) => {
//on login the user will be added to editors collection with default value of reviewer
console.log("hello from createeee");
// This is RTDB syntax for a ref
// const editorsRef = firebase.database().ref("editors");
// Try this instead
const editorsRef = firebase.firestore().collection("editors");
const editor = {
email: "user.email",
role: "reviewer",
lastSession: Date.now(),
};
// This is how you add an item to RTDB
// editorsRef.push(editor);
// This is the Firestore way to create a new record with a random, unique document id
await editorsRef.add(editor);
};
Not also that reads and writes with Firestore (just like RTDB) are asynchronous so you need to use async/await
(like I added) or then/catch
promises.
Upvotes: 1