Home > Software design >  How user can see their own data when they are logged in using Firebase
How user can see their own data when they are logged in using Firebase

Time:03-30

I am making a mobile app where i use Firebase as my backend-as-a-service. I am using Firebase SDK Authentication and Cloud Firestore from Firebase.

My problem is that i want a user to only see their own data when they are logged in. I saw that you could use your user-id in your database collection and then the document ID would be the user-id.

This is how far my code looks but it gives me error about that db.collection is not a function:

import { StyleSheet, Text, View, TextInput, Button } from 'react-native'
import React, {useState} from 'react'
import { auth, db } from '../../firebase/firebase'
import { collection, doc} from 'firebase/firestore';

export default function CreateUserComponent() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [username, setUsername] = useState('');
  const [firstname, setFirstname] = useState('');
  const [lastname, setLastname] = useState('');
  const usersCollectionRef = collection(db, "users");


  const handleSignUp = () => {
    auth
      .createUserWithEmailAndPassword(email, password)
      .then(userCredentials => {
        userCredentials.user;
      })
      .catch(error => alert(error.message))
  };

  const createUserData = async () => {
    auth
      .onAuthStateChanged(user => {
        usersCollectionRef.doc(user.uid).set({
          email: email,
          username: username,
          firstname: firstname,
          lastname: lastname,
          password: password
        })

      });
  }


  const handleSignUpAndPostData = () => {
    handleSignUp();
    createUserData();
  };

  return (
    <View style={styles.view}>
      <View>
        <Text style={styles.container}>CreateUserComponent: Welcome to your 
         registration</Text>
      </View>
     <View>
          <Text>E-mail:</Text>
          <TextInput style={styles.input} placeholder="Enter your email" value={email} 
           onChangeText={text => setEmail(text)}></TextInput>
          <Text>Username:</Text>
          <TextInput style={styles.input} placeholder="Enter your username" value= 
           {username} onChangeText={text => setUsername(text)}></TextInput>
          <Text>Firstname:</Text>
          <TextInput style={styles.input} placeholder="Enter your firstname" value= 
           {firstname} onChangeText={text => setFirstname(text)}></TextInput>
          <Text>Lastname:</Text>
          <TextInput style={styles.input} placeholder="Enter your lastname" value= 
           {lastname} onChangeText={text => setLastname(text)} ></TextInput>
          <Text>Password:</Text>
          <TextInput style={styles.input} secureTextEntry placeholder="Enter your 
           password" value={password} onChangeText={text => setPassword(text)}> 
          </TextInput>
      </View>
      <View style={styles.button}>
        <Button onPress={handleSignUpAndPostData} title= "Continue"/>
      </View>
    </View>
  )
}

const styles = StyleSheet.create({
    container: {
       fontSize: 16,
       fontWeight: 'bold',
       color: 'dodgerblue',
       marginTop: 100,
       padding: 20
    },
    view: {
       alignItems: 'center',
       justifyContent: 'center',
    },
    input: {
       borderWidth: 1,
       borderColor: '#777',
       padding: 8,
       margin: 10,
       width: 200,
       backgroundColor: 'white'
    },
    button: {
       marginTop: 20,
       width: "30%",
  }
})

This is the error messages it gives me: usersCollectionRef.doc is not a function UsersCollectionRef.doc(user.uid)

CodePudding user response:

According to your screenshots you have attached, the doc method does not exist on usersCollectionRef which is correct if you're using the modularized Firebase version.

Start here in the Firestore docs. For your use case, it will look like this:

import { doc, setDoc } from "firebase/firestore"; 

// ...

setDoc(doc(db, `users/${user.uid}`), { 
  // your data you want to write to Firestore
});

CodePudding user response:

Answer

Hey -

  1. Yes, using the user's uid from firebase authentication is a great system
  2. A best practice to query a user's documents is to add the user's uid as a field on their documents. That means adding a uid property on your Users collection that matches the users auth().currentUser.uid.

Some rationale and example

This allows you to easily query only the documents for a specific user.

For example, let's say you have a note-taking app with a "Users" collection for user profiles and a "Notes" collection to store each note in it's own document.

Each document in the "Users" collection would have a uid property, and each document in the "Notes" collection would also have a uid property.

To query the user's profile you query for Users.where("uid", ===, auth().currentUser.uid).limit(1)

To query all of this user's notes, you would do Notes.where("uid", ===, auth().currentUser.uid).

Additionally, if you had folders for notes in the app, you would add a folderId to each note.

Firestore was optimized for very large and flat document collections. You just need to make sure you are adding all of the proper ids to documents so that you can properly query them.

  • Related