0

I'm working with Firebase to retrieve data from the firestore, where I want to grab two groups of information, one would contain the "active" events, which the enddate is after the current date, and the "expired" dates, which enddates are before our current date. (My dates are stored as M/D/YYYY, ex: 6/7/2022

Variables I'm using:

const [events, setEvents] = useState([]);
const [expEvents, setExpEvents] = useState([]);
const today = new Date().toLocaleDateString();

My UseEffect:

    useEffect(() => {
        console.log("Fetching Events..")
        console.log(today)
        setLoading(true)
        const getEvents = async () => {
            const data = await getDocs(eventsRef);
            setEvents(data.docs.map((event) => ({...event.data()})))
            setExpEvents(data.docs.map((event) => ({...event.data()})))
        }
        getEvents()
        setExpEvents(expEvents.filter(event => Date.parse(event.enddate) < Date.parse(today)))
        console.log("Fetched Events!")
        setLoading(false) //done 
        console.log(events)
    }, [])

The issue I'm having is that it seems this filter statement is either incorrect, or getting overrided with something else, but I can't seem to understand why. Any help is appreciated.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441

1 Answers1

1

Well, you are using an async function without awaiting it to finish. Note that async should not be used for useEffect callbacks, so you need to refactor your code or use a promise with then, take a look here React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

Note also that a console.log after a state update would not log the updated value in any case, it logs the value that your state have when the function (the useEffect callback, in this case) is executed.

Emanuele Scarabattoli
  • 4,103
  • 1
  • 12
  • 21