简体   繁体   中英

How to show posts of only the logged in user from firestore in react native?

I want to show the posts of only logged in user in my dashboard. I'm creating a todo app where authenticated users can only see their todo list. I know I have to link the uid from auth with the firestore documents but I don't know the process.

Component where I add a new todo to the firestore and fetch the todos with snapshot method and send it to another component as props for rendering :


function Dash() {
  const [todo, setTodo ] = useState('');
  const [ loading, setLoading ] = useState(true);
  const [ todos, setTodos ] = useState([]);
  const ref = db.collection('todos');
  useEffect(() => {
    return ref.onSnapshot((querySnapshot) => {
      const list = [];
      querySnapshot.forEach(doc => {
        const { text, done } = doc.data();
        list.push({
          id: doc.id,
          text,
          done,
        });
      });

      setTodos(list);

      if (loading) {
        setLoading(false);
      }
    });
  }, []);
  
  async function addTodo() {
   await ref.add({
      done: false,
      text: todo,
      
    });

    setTodo('');
  }
  return(
  <>
  <Appbar>
    <Appbar.Content title={'TODOs List'} />
  </Appbar>
  <FlatList
        style={{flex: 1}}
        data={todos}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => <Todo {...item} />}
      />

 
  <TextInput label={'New Todo'} value={todo} onChangeText={(text) => setTodo(text)} />
  <Button onPress={() => addTodo()}>Add TODO</Button>
</>
  );
}

Component where I render the todos and display it in a List:

import React, {useContext, useState} from 'react';
import { ScrollView, Text, FlatList, StyleSheet, View, CheckBox, Alert } from 'react-native';
import { db }  from '../firebase/fire';
import { List, Button, Divider, Provider } from 'react-native-paper';
import { auth } from '../firebase/fire';
import {
  Menu,
  MenuOptions,
  MenuOption,
  MenuTrigger,
} from 'react-native-popup-menu';


function Todo({ id, text, done}) {
  const [user, setUser] = useState();
  const [visible, setVisible]= useState(false);
  const openMenu =() => setVisible(true);
  const closeMenu =() => setVisible(false);


  function deleteDoc(){
    db.collection('todos').doc(id).delete();
  }
  async function toggleComplete() {
    try{

    await db
      .collection('todos')
      .doc(id)
      .update({
        done: !done,
      
      });}
      catch
        (err){
          console.log(err);
        }
      }

  return (
    <List.Item
      title={text}
      left={props => (
        <Button {...props} icon={done ? 'check' : 'cancel'} onPress={() => toggleComplete()}/>
      )}
      right={()=>(
        <Button  icon='delete' onPress={() => deleteDoc()}/>
      )}
    />
    
  );
}
export default React.memo(Todo);

First, you would have to store UID of user in every new todo (document) that a user creates. Let's say we call that field 'userID'. Then you can query documents where that userID field is set to UID of current user.

To get UID of current user:

const uid = firebase.auth().currentUser.uid

Query to fetch user's documents:

const ref = db.collection("todos").where("userID", "==", uid)
ref.get().then((querySnapshot) => {
  const list = [];
  querySnapshot.forEach(doc => {
    const { text, done } = doc.data();
    list.push({
      id: doc.id,
      text,
      done,
    });
  });
  setTodos(list);
})

To make sure users can read/write their own documents, set proper security rules:

service cloud.firestore {
  match /databases/{database}/documents {
    match /todos/{todoID} {
      allow read, write: if request.auth != null && resource.data.userID == request.auth.uid;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM