chackerian
chackerian

Reputation: 1401

React functional component doesnt re-run firebase query

I'm trying to get a database request working for my functional component. The issue is the code only runs once and the database query doesn't update. When the user settings are changed, this screen doesn't update to reflect the changes. How can you get this behavior to work properly?

import React, { useState, useEffect, forceUpdate } from 'react'
import { Image, StyleSheet, Text, View, ScrollView } from "react-native";

import Button from './Button'
import Background from './Background'
import { useNavigation } from '@react-navigation/native';

import { storage, store } from "../App.js";

export default function Dashboard(props) {
  const navigation = useNavigation();
  const user = props.route.params.user
  const [name, setName] = useState('');
  const [about, setAbout] = useState('');
  const [interests, setInterests] = useState('');
  const [image, setImage] = useState('');

    console.log("TEST")
    var docRef = store.collection('users').doc(props.route.params.user.uid)
    docRef.get().then((doc) => {
      if (doc.exists) {
        console.log("DOC Dash", doc.data())
        setName(doc.data().name);
        setInterests(doc.data().interests);
        setAbout(doc.data().about);
        setImage(doc.data().photoURL)
        setLocation(doc.data().location)
      }
    });

  return (
    <Background>
    <View style={styles.container}>
    <Navbar />
      <View style={styles.info}>
        <Image source={{uri: image}} style={styles.image} />
        <Text style={styles.name}>{name}</Text>
        <View style={styles.details}>
          <Text>{location}</Text>
          <Text>{about}</Text>
          <Text>Interests: {interests}</Text>
        </View>
      </View>
    </View>
  </Background>
  )
}

Upvotes: 0

Views: 44

Answers (2)

Aakash Rathee
Aakash Rathee

Reputation: 593

What you are looking is getting realtime updates. Firestore realtime updates doc

The query should look something like this

store.collection('users').doc(props.route.params.user.uid).onSnapshot((doc) => {
 console.log("Current data: ", doc.data());
})

Upvotes: 1

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

To get realtime updates when the data changes, use onSnapshot instead of get:

docRef.onSnapshot((doc) => {

Also see the Firebase documentation on listening for realtime updates.

Upvotes: 0

Related Questions