簡體   English   中英

如何在反應原生中僅顯示來自firestore的登錄用戶的帖子?

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

我想在我的儀表板中顯示僅登錄用戶的帖子。 我正在創建一個待辦事項應用程序,其中經過身份驗證的用戶只能看到他們的待辦事項列表。 我知道我必須將來自 auth 的 uid 與 firestore 文檔相關聯,但我不知道這個過程。

我將一個新的待辦事項添加到 firestore 並使用快照方法獲取待辦事項並將其發送到另一個組件作為渲染道具的組件:


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>
</>
  );
}

我渲染待辦事項並將其顯示在列表中的組件:

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);

首先,您必須在用戶創建的每個新待辦事項(文檔)中存儲用戶的 UID。 假設我們稱該字段為“用戶 ID”。 然后,您可以查詢將userID字段設置為當前用戶的 UID 的文檔。

獲取當前用戶的 UID:

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

查詢以獲取用戶的文檔:

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);
})

為確保用戶可以讀/寫他們自己的文檔,請設置適當的安全規則:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM