wix / react-native-calendars

React Native Calendar Components 🗓️ 📆
MIT License
9.46k stars 2.93k forks source link

I can't get the TimelineList items to render. #2222

Open bskyper opened 1 year ago

bskyper commented 1 year ago

My brain is broke at this point. I'm trying to get the timeline list to appear here and for some reason it is not rendering the items. I know there is a lot of muck in the code right now because i've been trying various things. If anyone has any thoughts on what I may be doing wrong I would appreciate it.

`import React, { useState, useEffect } from "react"; import { StyleSheet, View, Text, TouchableOpacity, SafeAreaView, FlatList, } from "react-native";

import { Calendar, Agenda, Timeline, ExpandableCalendar, TimelineList, CalendarProvider, } from "react-native-calendars"; import Modal from "react-native-modal"; import FlightItem from "./FlightItem"; import UserStore from "../stores/UserStore"; import ReservationForm from "./ReservationForm"; import { db } from "../FirebaseConfig"; import { collection, addDoc, query, where, getDocs, onSnapshot, deleteDoc, doc, } from "firebase/firestore"; import { formatISO } from "date-fns";

const CalendarComponent = () => { const userDetails = UserStore; const [selectedDate, setSelectedDate] = useState( formatISO(new Date(), { representation: "date" }) ); const [isModalVisible, setIsModalVisible] = useState(false); const [selectedFlight, setSelectedFlight] = useState(null); const [editingReservation, setEditingReservation] = useState(null); //const [items, setItems] = useState({}); const [items, setItems] = useState({ [selectedDate]: [] });

const [refresh, setRefresh] = useState(false); // Move this line here //console.log(userDetails); const userID = userDetails.userID;

useEffect(() => { const currentDate = formatISO(new Date(), { representation: "date" }); if (currentDate) { loadReservations(currentDate); }

const reservationsRef = collection(db, "reservations");
const q = query(reservationsRef);
const unsubscribe = onSnapshot(q, (snapshot) => {
  const reservations = {};
  snapshot.forEach((doc) => {
    const data = doc.data();
    const date = data.date;

    if (!reservations[date]) {
      reservations[date] = [];
    }

    reservations[date].push({
      id: doc.id,
      start: data.startTime,
      end: data.endTime,
      title: `Aircraft: ${data.selectedAircraftValue}\n${data.firstName} ${data.lastName}`,
      color: aircraftColors[data.selectedAircraftValue] || "#000000",
    });
  });
  console.log("Updated reservations:", reservations);
  setItems(reservations);
});

return () => {
  unsubscribe();
};

}, [refresh]);

const onDayPress = (day) => { if (day.dateString) { setSelectedDate(day.dateString); loadReservations(day.dateString); } };

const onBookFlight = () => { setEditingReservation(null); setIsModalVisible(true); };

const aircraftColors = { N2875Z: "#FF0000", N6351Q: "#00FF00", N67890: "#0000FF", // Add more aircraft and colors as needed };

const onEditReservation = (reservation) => { setEditingReservation(reservation); setIsModalVisible(true); };

const loadReservations = async (date) => { const reservationsRef = collection(db, "reservations"); const q = query(reservationsRef, where("date", "==", date));

try {
  const querySnapshot = await getDocs(q);
  const newItems = { ...items };

  newItems[date] = [];

  await Promise.all(
    querySnapshot.docs.map(async (doc) => {
      const data = doc.data();
      const { id } = doc;

      newItems[date].push({
        id,
        start: data.startTime,
        end: data.endTime,
        title: `Aircraft ${data.selectedAircraftValue || "N/A"}\n${
          data.firstName
        } ${data.lastName}`,
        color: aircraftColors[data.selectedAircraftValue] || "#000000",
      });
    })
  );

  setItems(newItems);
} catch (error) {
  console.error("Error fetching reservations: ", error);
}

};

const addOrUpdateReservation = async (date, reservation) => { const reservationData = { date, userID: userDetails.userID, firstName: userDetails.first, lastName: userDetails.last, club: userDetails.club, ...reservation, selectedAircraftValue: reservation.selectedAircraftValue, // Add this line };

try {
  await addDoc(collection(db, "reservations"), reservationData);
  setIsModalVisible(false);
  setRefresh(!refresh); // Add this line to force a re-render
} catch (error) {
  console.error("Error adding reservation: ", error);
}

};

const handleDelete = async (id) => { // Delete the reservation from the database try { await deleteDoc(doc(db, "reservations", id)); setIsModalVisible(false); setRefresh(!refresh); } catch (error) { console.error("Error deleting reservation: ", error); } };

const onModalClose = () => { setSelectedFlight(null); setIsModalVisible(false); setEditingReservation(null); };

return (

{/* ...existing components... */} { console.log("Event pressed:", event); }} /> {/* Add Reservation Button */} + {/* Rest of your components */} {editingReservation ? "Edit Reservation" : "New Reservation"} { addOrUpdateReservation(selectedDate, reservation); }} onCancel={() => setIsModalVisible(false)} onDelete={() => handleDelete(editingReservation ? editingReservation.id : "") } editingReservation={editingReservation} editing={Boolean(editingReservation)} // Add this line />

); };

const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#F5FCFF", }, modalContainer: { backgroundColor: "white", borderRadius: 10, padding: 20, }, modalTitle: { fontSize: 18, fontWeight: "bold", marginBottom: 10, }, modalText: { fontSize: 16, marginBottom: 20, }, modalButtons: { flexDirection: "row", justifyContent: "flex-end", }, modalButton: { padding: 10, marginLeft: 10, backgroundColor: "#2196F3", borderRadius: 5, }, modalButtonText: { color: "white", fontWeight: "bold", }, emptyDataContainer: { flex: 1, alignItems: "center", justifyContent: "center", padding: 10, }, emptyDataText: { fontSize: 16, color: "#777", }, header: { flexDirection: "row", justifyContent: "space-between", alignItems: "center", paddingHorizontal: 20, paddingVertical: 10, backgroundColor: "#2196F3", }, headerTitle: { fontSize: 20, color: "white", fontWeight: "bold", }, headerButton: { paddingHorizontal: 10, paddingVertical: 5, borderRadius: 5, backgroundColor: "white", }, headerButtonText: { fontSize: 16, color: "#2196F3", fontWeight: "bold", }, addReservationButton: { position: "absolute", bottom: 20, right: 20, backgroundColor: "#2196F3", borderRadius: 50, width: 60, height: 60, justifyContent: "center", alignItems: "center", zIndex: 10, }, addReservationButtonText: { color: "white", fontSize: 40, }, });

export default CalendarComponent; `

CapSap commented 1 year ago

Hi bskyper, for me the events prop that feeds into TimeLineList looks like this:

  const dummyEvent2: TimelineListProps = {
    events: {
      '2023-04-01': [
        {
          start: '2023-04-01 09:20:00',
          end: '2023-04-01 12:00:00',
          title: 'Merge Request to React Native Calendars',
          summary: 'Merge Timeline Calendar to React Native Calendars',
        },
      ],
    },
  };

key point is that the format for the date key is 'yyyy-mm-dd'

stale[bot] commented 1 year ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

AdityaAA2004 commented 1 month ago

I am also not able to render the tasks. This is my task list: [ {"end": "2024-07-19T10:00:00", "start": "2024-07-19T09:00:00", "summary": "Summary for event 1", "title": "Event 1"}, {"end": "2024-07-19T12:00:00", "start": "2024-07-19T11:00:00", "summary": "Summary for event 2", "title": "Event 2"} ]

The component:

<Timeline
                events={taskListReformatted}
                format24h={true} // Set to false if you want 12-hour format
                start={0} // Start hour for the timeline (0 for midnight)
                end={24} // End hour for the timeline (24 for midnight)
                overlapEvents={false} // Set to true if events can overlap
                showNowIndicator={true}
                scrollToFirst={true}
            />
jossydeleon commented 2 weeks ago

I am also not able to render the tasks. This is my task list: [ {"end": "2024-07-19T10:00:00", "start": "2024-07-19T09:00:00", "summary": "Summary for event 1", "title": "Event 1"}, {"end": "2024-07-19T12:00:00", "start": "2024-07-19T11:00:00", "summary": "Summary for event 2", "title": "Event 2"} ]

The component:

<Timeline
                events={taskListReformatted}
                format24h={true} // Set to false if you want 12-hour format
                start={0} // Start hour for the timeline (0 for midnight)
                end={24} // End hour for the timeline (24 for midnight)
                overlapEvents={false} // Set to true if events can overlap
                showNowIndicator={true}
                scrollToFirst={true}
            />

Timeline renders events for a single date. Then you need to pass the date you want to render i the format below

<Timeline 
   ...props
   date={"2024-07-19"}
/>