Check value in firebase

hello,
i wish to check the data/value in firebase each time the user login via Google.
if data/value don’t exist then will write the signin email, username and membership into firebase database.
else, if data exist then no need write and direct fetch the membership value to the user profile page.

i’m jusing below blocks but after user signin the firebase database will have repeatedly writing the data inside. i’m not sure what’s wrong with my blocks.



data structure in firebase would be like this:

Have you get all emails in that global list?

What is the error you r facing now

Hi Mike,

You could use Firebase Function and create a .onCreate function that checks a node of your database, perhaps call it “members” with the emails of member users inside.

with the above blocks, in firebase database will continously write the same following data once call Web_userData.Get runs

now i need to take out the call checkUser blocks in order for me to fetch the whole email lists without trigger the continuous data writing again.

i don’t know why the call checkUser blocks will cause continous data writing into firebase database :downcast_face_with_sweat:

are you using any clock compo? where are you calling this procedure?

i got use clock component but is for different function and blocks.

firstly i will run call Web_userData.Got Text to pull data from firebase

second, after Web_userData Got Text then it will go to call checkUser

in to checkUser do above, it will check for any existing data/value in the firebase database, which if data don’t exist, it will write the name, email and membership values into database, else only pull value membership into a Label in profile page.

can you show me how please?
bcoz i haven’t go into this alternative yet

:repeat_button: Common Mistake:

In Kodular, many users mistakenly write to Firebase immediately after login, without waiting for Firebase’s value existence check (FirebaseDB.GetValue) to return. This leads to data being written every time, even if it already exists.

:white_check_mark: Correct Logic:

  1. User logs in via Google.
  2. Get user UID (or email).
  3. Check if /users/<uid> exists in Firebase Realtime Database.
  4. If exists:
  • Fetch membership data, show on profile page.
  1. If not exists:
  • Write user info (email, username, membership) to /users/<uid>.
  • Then, fetch membership data and show on profile page.

hi, can help to show how i should construct the blocks? :folded_hands:
i have tried the get tag list, get value also seems not working :smiling_face_with_tear:

Hi Mike,
explaining how the CLI works here would be a bit complicated, but the official guides are really well done and I’ve included them below.


Another way I can help is by sharing a function I wrote some time ago, which I managed to find again.

Function
const functions = require('firebase-functions/v1');
const admin = require('firebase-admin');

admin.initializeApp();

exports.onUserCreate = functions.auth.user().onCreate(async (user) => {
  const {
    uid,
    email = '',
    phoneNumber = '',
    displayName = '',
    photoURL = '',
    providerData,
    metadata
  } = user;

  const provider = providerData.length > 0 ? providerData[0].providerId : 'unknown';

  let username = '';
  if (email) {
    const localPart = email.split('@')[0];
    username = localPart.replace(/\./g, '_');
  }

  const userInfo = {
    uid,
    username,
    email,
    phone: phoneNumber,
    displayName,
    photoURL,
    provider,
    createdAt: metadata?.creationTime || new Date().toISOString()
  };

  try {
    await admin.database().ref(`YOURPROJECTBUCKET/users/${uid}/userinfo`).set(userInfo);
    console.log(`✅ User info saved for UID: ${uid}`);
  } catch (error) {
    console.error(`❌ Error saving user info for UID: ${uid}`, error);
  }

  return null;
});

As soon as a user logs in, the functions.auth.user().onCreate function creates a node in YOURPROJECTBUCKET/users/${uid}/userinfo containing all the Google/providerEmail data in this case: uid, username, email, phoneNumber, displayName, photoURL, and provider.
(I used to handle the username by retrieving everything before the “@” in the email for example, mario.rossi@gmail.com would become the username mario_rossi)

If you feel it’s too complex to manually edit, you could use an AI like ChatGPT to help you add or modify what you need.

1 Like

:wrench: BLOCK LOGIC OVERVIEW


:one: When Screen Initializes

Call Firebase_Auth.SignInWithGoogle

:two: When Firebase_Auth.GotUser

Set global uid to get idToken
Set global email to get Email

You can also use Firebase_Auth.CurrentUser to get UID.


:three: Check if user exists in Firebase DB

Call Firebase_DB.GetValue 
   tag = join "users/" and global uid

:four: When Firebase_DB.GotValue

if value ≠ "" then
   // User exists
   // Now fetch membership
   Call Firebase_DB.GetValue 
      tag = join "users/" and global uid and "/membership"
else
   // User doesn't exist
   // Write user info to Firebase
   Create empty dictionary:
     email = global email
     username = split at @ from email [e.g., left part]
     membership = "free"

   Call Firebase_DB.StoreValue
     tag = join "users/" and global uid
     value = dictionary

:five: After StoreValue – Get membership

When Firebase_DB.StoreValue
   Call Firebase_DB.GetValue 
      tag = join "users/" and global uid and "/membership"

:six: When GotValue (membership)

Set Label_Membership.Text = value

:white_check_mark: Optional: Show Email and Username

Set Label_Username.Text = global email (or parsed name)

:locked_with_key: Firebase Rules for This to Work

{
  "rules": {
    "users": {
      ".read": "auth != null",
      ".write": "auth != null"
    }
  }
}
1 Like

hi @SyntaxCore, appreciate for your reply on the block logic.

but now im thinking, i have database structure like below; how can i put such data into a meaningful structure so that later i can lookup a specific value for a specific key/tag.
for instance, if i want to know if “crispbytes@gmail.com” existed in the list/dictionary, then it will get the associated value under the “membership” key, then i want to bring this value to put on the label component at profile page.

i have been scratching my head on how to put the firebase data into multiple data pairs. because for below the format seems not right.

can anyone give me a guide for my questions above? :folded_hands:

i have tried this method but seems no luck :downcast_face_with_sweat:
blocks totally wrong?

:white_check_mark: Goal

  • Write user info (email, username, membership) only if it does not exist.
  • If user already exists, just fetch membership to show on profile page.

:white_check_mark: Firebase Setup (Structure Suggestion)

nginx

CopyEdit

FirebaseDB
└── users
    └── userUID
        ├── email: "user@example.com"
        ├── username: "JohnDoe"
        └── membership: "Free"

:white_check_mark: Variables (Create global variables)

  • global userUID
  • global userEmail
  • global userName
  • global userMembership

:white_check_mark: Full Logic (Kodular Blocks Breakdown)

1. After Google Login Success

blocks

CopyEdit

When GoogleSignIn1.Got ID Token do:
   Set global userUID to GoogleSignIn1.UserID
   Set global userEmail to GoogleSignIn1.Email
   Set global userName to GoogleSignIn1.DisplayName
   Call FirebaseDB.Get Value
       tag = join "users/" and global userUID
       valueIfTagNotThere = "NOT_FOUND"

2. Firebase Got Value (Check if User Exists)

blocks

CopyEdit

When FirebaseDB.Got Value do:
   If value = "NOT_FOUND" then
       // User doesn't exist, write data
       Call FirebaseDB.Store Value
           tag = join "users/" and global userUID
           value = make a dictionary with:
               "email" → global userEmail
               "username" → global userName
               "membership" → "Free"

       // Optionally, set global userMembership to "Free"
       Set global userMembership to "Free"

   else
       // User exists, get membership from value
       Set global userMembership to value["membership"]

:warning: Important Notes

  • Do not call FirebaseDB.Store Value unless you’ve confirmed the value is "NOT_FOUND".
  • The key thing is comparing the returned value and using a sentinel value like "NOT_FOUND" to detect absence.
  • Ensure your Firebase rules allow .read access for the path you’re checking.

I have this blocks .Test and enjoy

hi @SyntaxCore,

much appreciated for your blocks, but the value for “membership” tag not writing to the label.
is it need to use the “userid” blocks?


others such as data written to firebase database can work correctly.

Can you show me your blocks?Make sure spellings



here’s my blocks and i got rename the “userid” to “userID” (naming only, should be no issue right?).

I got the error: just convert the else if to else, and it works fine.

It should be written if there is not value in memebership but it empty means value get but empty. I thing we go on a debug