React Firebase 数据未定义

发布于 2025-01-11 16:54:14 字数 1886 浏览 0 评论 0原文

我正在尝试建立一个金融科技网站,并且我有一个用户集合和一个交易集合。一个用户可以使用另一用户的电话号码向其汇款。

用户架构包含这些

uid - string
phone - string
.....//other data

我需要实现以下功能

  1. 输入目标接收者的电话号码
  2. 获取具有输入电话号码的用户的详细信息
  3. 将此数据添加到另一个称为交易的集合

我尝试这样做,但我遇到了一个错误第三步,第二步的数据未定义。这是我的代码

const SendMoney = () => {

    const [receiverDetails, setRecieverDetails] = useState({})
    const [allUsers, setAllUsers] = useState([])
    const [receiverphone, setReceiverphone] = useState('')

    const usersCollectionRef = collection(db, "users")
    const getAllUsers = async () => {
        const data = await getDocs(usersCollectionRef)
        setAllUsers(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
    }

    useEffect(() => {
        getAllUsers()
    }, [])

    const getRecieverDetails = (phone) => {
        const receiver = allUsers.filter(u => u.phone === phone)[0]
        setRecieverDetails(receiver)
    }

    const makeTransaction = async () => {
        getRecieverDetails(receiverphone)
        console.log(receiverDetails)  --------> prints {}

        
        const transactionsCollectionRef = collection(db, "transactions")
        await addDoc(transactionsCollectionRef,
            {
                toUser: receiverDetails.uid,
                //other data
            }
        )
    }

    return (
        <div>
            <h2>Send money</h2>
            <input placeholder='phone number' onChange={e => setReceiverphone(e.target.value)} />
            <input type="number" onChange={e => setAmount(e.target.value)} />
            <button onClick={makeTransaction}>send money</button>
        </div>

    )
}

export default SendMoney

我的猜测是在 receiveDetails 填充数据之前调用 addDoc 函数。我不知道如何修复这个错误

I'm trying to build a fintech website, and I have a users collection and a transactions collection. One user can send money to another user by using their phone number.

The user schema contains these

uid - string
phone - string
.....//other data

I need to achieve the following functionality

  1. Enter phone number of target receiver
  2. Get details of user with the entered phone number
  3. Add this data to another collection called transactions

I tried doing that, but I'm getting a bug that in the 3rd step, the data from the 2nd step is undefined. Here's my code

const SendMoney = () => {

    const [receiverDetails, setRecieverDetails] = useState({})
    const [allUsers, setAllUsers] = useState([])
    const [receiverphone, setReceiverphone] = useState('')

    const usersCollectionRef = collection(db, "users")
    const getAllUsers = async () => {
        const data = await getDocs(usersCollectionRef)
        setAllUsers(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })))
    }

    useEffect(() => {
        getAllUsers()
    }, [])

    const getRecieverDetails = (phone) => {
        const receiver = allUsers.filter(u => u.phone === phone)[0]
        setRecieverDetails(receiver)
    }

    const makeTransaction = async () => {
        getRecieverDetails(receiverphone)
        console.log(receiverDetails)  --------> prints {}

        
        const transactionsCollectionRef = collection(db, "transactions")
        await addDoc(transactionsCollectionRef,
            {
                toUser: receiverDetails.uid,
                //other data
            }
        )
    }

    return (
        <div>
            <h2>Send money</h2>
            <input placeholder='phone number' onChange={e => setReceiverphone(e.target.value)} />
            <input type="number" onChange={e => setAmount(e.target.value)} />
            <button onClick={makeTransaction}>send money</button>
        </div>

    )
}

export default SendMoney

My guess is that the addDoc function is called before the receiverDetails gets populated with data. I am not sure how to fix this bug

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

池予 2025-01-18 16:54:15

setStateuseState 挂钩的 setter 的调用是异步的。

不要使用状态在您自己的代码片段之间传递数据,而是使用普通变量,并使用 Promise 或 async/await 进行同步。

const SendMoney = () => {
const [receiverDetails, setRecieverDetails] = useState({})
const [allUsers, setAllUsers] = useState([])
const [receiverphone, setReceiverphone] = useState('')
let users; //

Calls to setState or the setter of a useState hook are asynchronous.

Don't use state to pass data between your own pieces of code, but instead use normal variables, and promises or async/await to synchronize.

const SendMoney = () => {
    const [receiverDetails, setRecieverDetails] = useState({})
    const [allUsers, setAllUsers] = useState([])
    const [receiverphone, setReceiverphone] = useState('')
    let users; // ???? new variable

    const usersCollectionRef = collection(db, "users")
    const getAllUsers = async () => {
        const data = await getDocs(usersCollectionRef)
        users = data.docs.map((doc) => ({ ...doc.data(), id: doc.id })); // ???? This is synchronouse
        setAllUsers(users); // ???? This is asynchronous
    }

    useEffect(() => {
    }, [])

    const getRecieverDetails = (phone) => {
        await getAllUsers()
        const receiver = users.filter(u => u.phone === phone)[0]
        setRecieverDetails(receiver)
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文