Home > database >  add a class constructor as a value in firebase
add a class constructor as a value in firebase

Time:03-31

I want to create a inbox and message system for my app, so I made a class called Inbox which would hold all the information for this.

But when I try and add the class to a firebase document, it gives the error Uncaught (in promise) FirebaseError: Function setDoc() called with invalid data. Unsupported field value: a custom Inbox object (found in field inbox in document users/--insert id here--)

Here's my code:

export const signup = (fname, lname, username, email, password, callback) => {
  createUserWithEmailAndPassword(auth, email, password)
    .then((callback) => {
      user = callback;
      logEvent(analytics, "sign_up", {
        id: user.user.uid,
      });
      setDoc(doc(firestore, "users", `${user.user.uid}`), {
        fname: fname,
        lname: lname,
        username: username,
        email: email,
        bullet: 1000,
        blitz: 1000,
        rapid: 1000,
        classical: 1000,
        chess960: 1000,
        kingOfTheHill: 1000,
        threeCheck: 1000,
        antichess: 1000,
        atomic: 1000,
        horde: 1000,
        racingKings: 1000,
        crazyhouse: 1000,
        losers: 1000,
        games_played: 0,
        games_won: 0,
        games_lost: 0,
        games_drawn: 0,
        games_forfeited: 0,
        uid: user.user.uid, 
        inbox: ---> new Inbox(), // error!
        friends: ---> new Friends(), // error!
      }).then(() => {
        callback();
      });
    })
    .catch((err) => {
      throw err;
    });
};

I'm using firebase version ^9.6.3 and react. Is there any workaround or alternative method to do this?

CodePudding user response:

As already pointed out in the comments, Firestore cannot store functions (or constructors for that matter). From my perspective, you have two options:

Option 1

Serialize your functions as a string, store them in Firestore, then eval them on the client. But that's pretty terrible.

Option 2

Adjust your data model in Firestore. From the looks of it the collection "users" should either have two sub-collections "inbox" and "friends" or you could make "inbox" and "friends" root-level collections and reference the user they belong to (so you can query them like collection('friends').where('uid', '==', userId) or something like this).

In general, I always take all the pieces of data apart and try to structure them in the most independent manner possible. Don't shoehorn your client logic into your data model. This is a recipe for tedious refactors later on when your client logic will eventually change.

  • Related