0

I'm trying to get an array of all users saved in my firestore, but it pulls only from the moment the app was started and not after creating a new user.

ClientsList.js

import React from 'react'
import {
  Text,  
  StyleSheet,
  ScrollView
} from 'react-native';

import Background from '../components/Background'
import Header from '../components/Header'

import { listClients } from '../helpers/clientManager'

const ItemView = (item) => {
    return (  
      <Text  
        key={item.id}
        style={styles.itemStyle}  
        onPress={() => 
          getItem(item)
        }>  
        {item.id}  
        {' - '}  
        {item.nome.toUpperCase()}  
      </Text>  
    );  
};

const getItem = (item) => {  
    alert(
        `Cliente: ${item.nome}\n` +
        `Cadastro: ${item.cadastro}\n` +
        `Entrega: ${item.entrega}\n` +
        `ID: ${item.id}\n` +
        `Produtos: \n\n${item.produtos.map(p => `Nome: ${p.title} \nQuantia: ${p.amount} \nValor: R$ ${p.value} \n--------------`).join("\n")}`
    );  
};

export default function ClientsList({ navigation }) {

  (async function () {
    data = await listClients()
    
    return data
  })()

  return (
    <Background>
        <Header>Lista de todos os clientes atuais.</Header>
        <ScrollView>
            {
                    data.map(ItemView)
            }
        </ScrollView>
    </Background>
  )
}

const styles = StyleSheet.create({  
    container: {  
      paddingTop: 40,  
      backgroundColor: 'white',  
    },  
    itemStyle: {  
      backgroundColor: '#0066CC',  
      padding: 10,  
      marginVertical: 8,  
      marginHorizontal: 10,  
      color: 'white' 
    },  
  });

clientManager.js

import { firebase } from './firebase'

const usersRef = firebase.firestore().collection('clientes')

export async function listClients(id) {
    let docsAll = await getMarkers()

    return docsAll
}

async function getMarkers() {
    const markers = [];
    await firebase.firestore().collection('clientes').get()
      .then(querySnapshot => {
        querySnapshot.docs.forEach(doc => {
        markers.push(doc.data());
      });
    });
    return markers;
  }

I need to know a method of having this information in real time, since I have no idea (or if I forgot something basic) how to get them.

1 Answers1

0

That's because you're calling get(), which loads data only once - when the code executes.

If you want to continue to monitor the database for changes, you should use a real-time listener - with the onSnapshot method. This is typically done in a useState hook, so that you can attach the listener to the database when the component is added to the UI, and detach the listener when the component is removed from the UI.

For examples of how to do this, have a look at these questions and their answers:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807