I hava data structured like the following being fetched from firebase:
const shows = [
{
name: 'one',
date: '2022-04-24T20:00',
},
{
name: 'two',
date: '2022-04-26T20:00',
},
{
name: 'three',
date: '2022-04-29T20:00',
},
{
name: 'four',
date: '2022-05-10T20:00',
},
{
name: 'five',
date: '2022-05-12T20:00',
},
{
name: 'six',
date: '2022-06-10T20:00',
},
]
When mapping through the data I want to have a ‘month bar’ announcing the beginning of each new month and achieve something like this:
Month April
One - 2022-04-24T20:00
Two - 2022-04-26T20:00
Three – 2022-04-29T20:00
Month May
Four – 2022-05-10T20:00
Five – 2022-05-12T20:00
Month June
Six – 2022-06-10T20:00
The data of course contains much more dates and I have also set limit and a load-more button when fetching from firebase. My code right now looks like below and the only idea I’ve had, which doesn’t work, is to create a useState called showDate and change compare it to the date when mapping the array…
import React, { useEffect, useState } from 'react';
import db from './firebase-config';
import { collection, where, query, limit, startAfter, getDocs } from "firebase/firestore";
function App3() {
const [shows, setShows] = useState([{namn: 'loading...', id: 'loading'}]);
const [lastVisible, setLastVisible] = useState();
const [isEmpty, setIsEmpty] = useState(false);
const [showDate, setShowDate] = useState();
useEffect(() => {
const getData = async () => {
const q = query(collection(db, "shows"), limit(3));
const noData = q.size === 0;
if(!noData){
const showData = await getDocs(q);
const newShows = showData.docs.map((doc) => ({...doc.data(), id: doc.id }));
setShows(newShows);
setLastVisible(showData.docs[showData.docs.length-1]);
}else{
setIsEmpty(true)
console.log('no more');
}
};
getData();
}, []);
const getNextData = async () => {
const q = query(collection(db, "shows"), startAfter(lastVisible), limit(3));
const showData = await getDocs(q);
const noData = showData.size === 0;
if(!noData){
const newShows = showData.docs.map((doc) => ({...doc.data(), id: doc.id }));
setShows((shows) => [...shows, ...newShows]);
setLastVisible(showData.docs[showData.docs.length-1]);
}else{
setIsEmpty(true)
console.log('no more');
}
}
return (
<div>
{
shows.map((show) => ( (new Date (show.date).getMonth() !== showDate) ?
(<div>Month {new Date(show.date).getMonth()}</div>):
(new Date (show.date).getMonth() !== showDate) ?
(setShowDate(new Date(show.date).getMonth())) :
(<div key={show.id}>{show.name}–{show.date}</div>)
))
}
{!isEmpty && <button onClick={getNextData} >More</button>}
{isEmpty && <div>Nothing more to show</div>}
</div>
);
}
export default App3;
Any thoughts on what the best way of achieving this could be? Thanks!