How to get data from Firebase v9 RT db in React Native without causing infinite loop

Viewed 41

I am trying to fetch some simple data from my Firebase real-time database within a React Native app. I am using the Firebase SDK (v9.9.3). With my current code implementation, I get stuck in an infinite loop and I am not sure why. How do I read the data correctly?

App.js

import EventCountdown from "./components/EventCountdown";
return(
...
<EventCountdown />
);

then inside of EventCountdown.js

import { View, Text, StyleSheet } from "react-native";
import { GlobalStyles } from "../../constants/styles";
import { useState } from "react";
import { getData } from "../../util/database";

export default function EventCountdown() {
    const [nearestEvent, setNearestEvent] = useState({name: "None", location: "N/A", date: "None", daysUntil: 999});
    const [events, setEvents] = useState();

    getData('events', setEvents);
    // Returns object of objects so convert to an array of objects
    const eventData = events != null ? Object.values(events) : null;
    const today = new Date();

    if (eventData != null) {
        for (let event of eventData) {
            const date = new Date(event.date);
            const daysUntilEvent = Math.ceil((date.getTime() - today.getTime())/(1000*3600*24));
            const dateInFuture = date > today;
            if ((daysUntilEvent < nearestEvent.daysUntil) && dateInFuture) {
                setNearestEvent({
                    name: event.name,
                    location: event.location,
                    date: date,
                    daysUntil: daysUntilEvent
                });
            }
        }
    }

    return (
        <View style={styles.countdownContainer}>
            <View style={{flex: 1}}>
                <Text style={styles.daysRemaining}>{nearestEvent.daysUntil}</Text>
                <Text style={styles.eventName}>{nearestEvent.name}</Text>
            </View>
        </View>
    );
}

and finally the getData function,

import { db } from '../firebase/firebase-config';
import { ref, onValue, set } from 'firebase/database';

export function getData(path, setData) {
    const dataRef = ref(db, path);
    onValue(dataRef, (snapshot) => {
        if (snapshot.exists()) {
            const data = snapshot.val();
            setData(data);
        } else {
            Alert.alert('No data', 'No data available at location specified');
        }
    });
}

Many..many...thanks :)

1 Answers

Never call any function like this getData normally in a function, , use useEffect for that

useEffect(() => {
getData('events', setEvents);
},[getData])

Hope this will solve the issue, if it doesnt lemme know

Related