Привет, как мне заставить firebase обновлять мои данные в реальном времени? - PullRequest
0 голосов
/ 08 мая 2020

Текущая настройка, которая у меня есть, извлекает данные firebase всякий раз, когда загружается страница, это было здорово, но теперь мне нужны данные в моем приложении для обновления в режиме реального времени, как мне это сделать?

useEffect(() => {

    const user = Authentication.auth().currentUser;
    {
        user !== null &&
            Authentication.firestore().collection('Health_data')
                .doc(user.uid)
                .get()
                .then(doc => {
                    healthDataSet(doc.data())
                    setLoading(false)
                }).catch(function (error) {
                    console.error("Error reading health", error);
                });
    }
    return () => {
        document.body.style.overflow = 'unset';
    }

}, []);

//calculates calorie requirments
useEffect(() => {
    if (!loading && healthData !== null) {


        if (healthData.units === 'Kg') {
            BMIset(Math.round((healthData.weight / ((healthData.height / 100) * (healthData.height / 100))) * 10) / 10)


                if (healthData.gender === 'female') {
                    BMRset(Math.round(((655.1 + (9.563 * healthData.weight) + (1.850 * healthData.height) - (4.676 * healthData.age)) * 1.37) * 0.8))
                } else {
                    BMRset(Math.round(((88.2 + (13.362 * healthData.weight) + (4.799 * healthData.height) - (5.677 * healthData.age)) * 1.37) * 0.8))
                }

            }

            if (healthData.goal === 'Gain') {

                if (healthData.gender === 'female') {
                    BMRset(Math.round(((655.1 + (9.563 * healthData.weight) + (1.850 * healthData.height) - (4.676 * healthData.age)) * 1.37) * 1.2))
                } else {
                    BMRset(Math.round(((88.2 + (13.362 * healthData.weight) + (4.799 * healthData.height) - (5.677 * healthData.age)) * 1.37) * 1.2))
                }

            }

            if (healthData.goal === 'Recomp') {
                if (healthData.gender === 'female') {
                    BMRset(Math.round((655.1 + (9.563 * healthData.weight) + (1.850 * healthData.height) - (4.676 * healthData.age)) * 1.37))
                } else {
                    BMRset(Math.round((88.2 + (13.362 * healthData.weight) + (4.799 * healthData.height) - (5.677 * healthData.age)) * 1.37))
                }

Итак, вот мой код после того, как данные извлечены, данные используются для вычислений. Я хочу, чтобы при обновлении данных вот так.

  const updateWeight = () => {
        if (Weight !== null) {
            database.collection('Health_data').doc(localStorage.getItem('user')).update({
                weight: Weight
            }).catch((error) => {
                alert(error.message)
                console.log('failed to write', error);
            });
        } else {
            alert('A weight must be in put')
        }
    }
* 1006 это возможно?

1 Ответ

1 голос
/ 08 мая 2020

Вы можете прослушать документ с помощью метода onSnapshot () . Первоначальный вызов с использованием предоставленного вами обратного вызова сразу же создает моментальный снимок документа с текущим содержимым одного документа. Затем каждый раз, когда содержимое изменяется, другой вызов обновляет моментальный снимок документа.

Для получения дополнительных сведений перейдите по ссылке:
https://firebase.google.com/docs/firestore/query-data/listen#web_1

...