React Native calendar agenda not displaying events with identical dates

I am currently utilizing the React Native Calendars library to develop an agenda-style application with React Native. To fetch the necessary data, I am leveraging the Firebase Firestore library.

The agenda functionality of this library relies on several properties to display appointment cards:

Here are my agenda settings:

          <Agenda
            items={agenda.items}
            // Initially selected day
            selected={date}
            // Minimum date that can be selected, dates before minDate will be grayed out. Default = undefined
            minDate={today}
            // Specify how each item should be rendered in agenda
            renderItem={(item, firstItemInDay) => {
                return <View>
                    <PlanningCard
                    style={styles.appointmentCard}
                    hour={String(moment.unix(item.date).format("H[h]mm"))}
                    ></PlanningCard>
                </View>;
            }}
            />

This is the data returned from my function -->props

This is the function I invoke, and it's quite convoluted as I'm striving to gather all the information needed for both the calendar and agenda displays.

export const retrievePlanning = async (uid:string) => {
    let getAppointments:any;
    let appointments:any = {};
    let markedDates:any = {};
    let agendaItems:any = {};
    let user:any;
    let docDate:string;
    
    let today:string = String(moment().format("YYYY-MM-DD"));

    try{

        getAppointments = await firestore()
                                .collection('appointments')
                                .where('marchand_id', '==', uid)
                                .get(); // Retrieve
        
        getAppointments.forEach(async(doc:any) => { // Iterate through appointments

            appointments[doc.id] = doc.data(); // Store appointments
            docDate = moment.unix(doc.data().date).format("YYYY-MM-DD"); // Convert Unix timestamp to agenda date format
            markedDates[docDate] = {marked: true, dotColor: 'deepskyblue'} // Track appointment dates (for calendar markers)

            try {
                user = await firestore()
                            .collection('users')
                            .doc(String(doc.data().customer_id))
                            .get(); // Obtain user associated with appointment
                
                console.log("test, does this work??")

                // HERE IS THE ISSUE !!!
                            
                agendaItems[docDate] = [doc.data(), user.data()] // Store appointment dates (to display them as agenda items)

                
            } catch (error:any) {
                console.log(error);
                Alert.alert("Error", String(error.message));
            }

        });

        //console.log(agendaItems)
        //console.log(calendarDates)
        //console.log(planning);

        return {planning: appointments, dates: markedDates, items: agendaItems}

    } catch (error:any) {
        console.log(error);
        Alert.alert("Error", String(error.message));
    }
    
}

The issue arises within the appointments loop, where I aim to fetch multiple appointments with the same date but distinct hours.

I need to establish an object that holds three types of information:

  • Formatted appointment dates (for calendar markers)
  • Complete data from each individual appointment (to transmit as props to the next screen)
  • Formatted appointment dates + appointments data + user data (for displaying agenda cards)

The predicament is that I am unable to append multiple values under the same index (the indexes being the dates). For instance, if there are two appointments on the same day, it should look like this:

{ 
  "2022-01-24": [{appointment 1 data}],
  "2022-01-24": [{appointment 2 data}],
  "2022-01-28": [{some other appointment data}],
}

Instead, it appears like this:

{ 
  "2022-01-24": [{appointment 2 data}],
  "2022-01-28": [{some other appointment data}],
}

This means that only one appointment can be displayed per day. Is there a way to achieve the example above? Or is there any workaround or solution?

PS: English is not my first language, so please excuse any grammatical errors. Also, I am relatively new to programming, so this code may seem messy.

Answer №1

To achieve the desired outcome, follow these steps:

  1. Go through each of your appointments and set up an empty array for each key
  2. Go through your appointments again and assign each appointment to its respective date in the array

Here is a breakdown of the process:

Step 1:

for(appointment of appointments){
   items[formatDate(appointment.date,'YYYY-MM-DD')] = []; 
 }

Step 2:

for(appointment of appointments){
   items[formatDate(appointment.date,'YYYY-MM-DD')].push({
      // Add your agenda item here
    }) 
 }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customizing Tab Navigation in React using TypeScript Parameters

Currently, my project involves developing projects using Typescript in conjunction with the React Native library. One specific task I am working on is creating a Custom Tab Bar and the necessary parameters include state, descriptors, and navigation. When ...

What is the rationale behind permitting interface method implementations to have varying intersection type arguments?

The interface and implementation presented here are quite straightforward: class Transform { X: number = 0 Y: number = 0 } class RenderData { Model: object | null = null } interface System { Update(e: Transform & RenderData): void } class Ren ...

How can we assign a default value to a select element that is part of an *ngFor iteration in Angular 14?

While browsing another forum, I stumbled upon this particular post where someone claimed to have already solved the issue I'm facing. However, no matter how hard I try, I can't seem to get it to work in my own code. Within my component, I have tw ...

Can you identify the issue in this TypeScript code?

As a newcomer to Angular and Typescript, I decided to watch some YouTube tutorials to better understand these technologies. I stumbled upon this particular tutorial which I followed along by copying the code. Within the component I'm working on, I at ...

Issues with updating form inputs in Ionic 2's FormGroup item

Hey there, I'm just getting started with Angular 2 and I've been working on creating a basic form using FormBuilder and FormGroup. However, for some reason, the value I input into the username field in my view is not updating in my component. Whe ...

Fundamental Guidelines for Firebase

I've recently started working with Firebase and I'm encountering some issues with the security rules. My project is a blog website where visitors can read posts, users, and comments without being logged in. However, logged-in and verified users ...

Encountering an error when attempting to reach a JSON endpoint using Javascript and X-Auth-Token

I'm attempting to retrieve data from a JSON endpoint using JavaScript and X-Auth-Token, but I am continuously encountering errors. The data is from a sports API, and despite diligently following all the instructions in the documentation and checking m ...

Setting up VSCode to run various tasks

My TypeScript project in Visual Studio Code has a specific task outlined as follows: { "version": "0.1.0", // The command is tsc. "command": "tsc", // Show the output window only if unrecognized errors occur. "showOutput": "silent", // Und ...

Error in Angular6: Why can't handleError read injected services?

It appears that I am facing an issue where I cannot access a service injected inside the handleError function. constructor(private http: HttpClient, public _translate: TranslateService) { } login(user: User): Observable<User> { ...

Steps to successfully transmit a JSON array to a remote ASMX web service using C#

I am currently working on an application where I need to send a request to a remote asmx web service that requires several parameters. One of the parameters is expecting a JSON array input, but I'm struggling to figure out how to correctly include thi ...

What is the best way to insert a new value into an already existing JSON array?

My JSON structure looks like this: { "intents": [ { "tag": "greeting", "patterns": [ "Hi there", "How are you", ...

In Angular 16, allow only the row that corresponds to the clicked EDIT button to remain enabled, while disabling

Exploring Angular and seeking guidance on a specific task. I currently have a table structured like this: https://i.stack.imgur.com/0u5GX.png This code is used to populate the table: <tbody> <tr *ngFor="let cus of customers;" [ngClass ...

Error message occurs when attempting to access an array generated from JSON data

Today, I've been experimenting with JSON, PHP, and JS, but I'm encountering some issues. The PHP code functions correctly, retrieving a row of data from my SQL table and encoding it as JSON. My JS/JQuery script successfully loads the data from t ...

Guide on effectively converting a table of tuples to an array of objects utility function (similar to zip) while preventing the merging of all values in typescript version 5.2.2

Almost there, but stuck on the final TS2322: Type TcolTuple[i] is not assignable to type string | number | symbol compiler error. Here's a nifty utility function called rowsToObjects() that many developers have probably come up with at some point, ...

Error parsing JSON: The file contains multiple JSON documents, but a property name is expected to be enclosed in double quotes

My search efforts on Google have been fruitless in finding a solution to the persistent error I am encountering: JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 1 (char 2) The issue arises at this line in my Python file: ...

Executing API call utilizing the Request module within a node.js application

In my node.js app, I have a request call that looks like this: request({ url:chanURL, qs:chanProperties}, function(err, response, body) { if(err) { console.log(err); return; } body = JSON.parse(body); (function (body) { Objec ...

The declaration file for the module 'vue-html-to-paper' was not located

Struggling to make a sample project work with HTML to PDF, but encountering an error message stating: Could not find a declaration file for module 'vue-html-to-paper' Even though it resides in my node_modules index.js import Vue from 'vue& ...

Using Typescript to set a variable's value from an asynchronous function

Could someone help me with a challenge I am facing while using Typescript? I am attempting to assign the return value from an async service call to a local variable like this: private searchResult; public search():void{ this.DashboardServi ...

Exporting External JavaScript Variables in Angular 2 Using Typescript

In my Configuration JS file, I have defined some configuration variables. For example: var config = {url:"xyz.com"}; I need to access these configuration parameters throughout my application. I attempted to export the config variables like this: export ...

Use TypeScript to selectively return a portion of the interface

I am faced with a User interface structured as follows interface IUser { name: string, phoneNumber: string } and another interface called PublicUser structured like this interface IPublicUser { name: string } The goal is to extract only publ ...