FirebaseError: Function addDoc() called with invalid data
I'm trying to create user collection in Firebase using addDoc function. When I run it in component it works but when I dispatch it from Vuex displays that error
vuex.esm-browser.js?5502:1057 Uncaught (in promise) FirebaseError: Function addDoc() called with invalid data. Unsupported field value: a function (found in field username.dispatch in document users/ULLwEmHPaYcRnaN7EFgW)
firebase config.js
import { initializeApp } from "@firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore, collection, getDocs, addDoc } from "firebase/firestore";
const firebaseConfig = {
apiKey: process.env.VUE_APP_FIREBASE_API_KEY,
authDomain: process.env.VUE_APP_FIREBASE_AUTH_DOMAIN,
projectId: process.env.VUE_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.VUE_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.VUE_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.VUE_APP_FIREBASE_APP_ID,
measurementId: process.env.VUE_APP_FIREBASE_MEASUREMENT_ID,
};
initializeApp(firebaseConfig);
const db = getFirestore();
const users = collection(db, "users");
const auth = getAuth();
export { db, auth, getDocs, users, addDoc };
store index.js
import { createStore } from "vuex";
import { auth, addDoc, users } from "../config/firebase";
actions: {
async createUser(username, email) {
await addDoc(users, {
username: username,
email: email,
});
},
createUser Function in component
const userData = reactive({
email: "",
userName: "",
});
const createUserWithEmailAndPassword = async () => {
store.dispatch("createUser", userData.email, userData.userName);
console.log("userData :>> ", userData);
};
Action function has to have first argument as context then arguments.
Like bellow.
async createUser(context, username, email) {
await addDoc(users, {
username: username,
email: email,
});
},
Error you getting is that field username
in addDoc()
function is object and not a string.
If you enable persistance in firestore you no need vuex. It's just a small tip. Vuex might be only neded if you for example want to store some temporary data like shop cart and you don't want to save them until user will acually buy them. I use vuex if i want to popup some snack on user screan with information like "Success! Data: XXXXXXXXXX was saved.".