0

I am trying to display previously created events on my calendar page using a fetch events function. I have made an api that has a route to fetch events from my database. In my database, when an event is created, it has a specific event id and also gets the carpool id under which it was created put onto it. It also has an event date property.

This is my api route to fetch specific events based on the day:

app.get('/api/events/:carpoolID/:eventID', async (req, res) => {
    const { carpoolID, eventID } = req.params;

    // Validate the UUIDs
    if (!isUuid(carpoolID) || !isUuid(eventID)) {
        return res.status(400).json({ error: 'Invalid carpoolID or eventID format.' });
    }

    try {
        // Fetch the event details from the database
        const query = 'SELECT * FROM "events" WHERE carpool_id = $1 AND event_id = $2';
        const queryResult = await db.query(query, [carpoolID, eventID]);

        if (queryResult.rows.length === 0) {
            return res.status(404).json({ error: 'Event not found.' });
        }

        // Return the event details
        res.status(200).json(queryResult.rows[0]);
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

This is my fetchDailyEvents function code:

 func fetchDailyEvents() {
        print("Fetching Events")

        guard let userIDString = UserDefaults.standard.string(forKey: "userID"),
              let userID = UUID(uuidString: userIDString) else {
            print("User ID not found in UserDefaults or invalid UUID string")
            return
        }

        WebService.fetchGroupData(carpoolID: userID) { result in
            switch result {
            case .success(let group):
                let carpoolIDString = group.carpoolID.uuidString
                print("Carpool ID fetched successfully:", carpoolIDString)

                let group = GroupT(
                    carpoolID: group.carpoolID,
                    carpoolName: group.carpoolName,
                    admin: group.admin,
                    members: group.members,
                    date_created: group.date_created,
                    events: group.events
                )

                let viewModel = EventViewModel(group: group)
                viewModel.fetchDailyEvents(forCarpoolID: carpoolIDString, date: dateForCell()) { result in
                    switch result {
                    case .success(let events):
                        DispatchQueue.main.async {
                            self.events = events
                        }
                    case .failure(let error):
                        print("Error fetching events: \(error)")
                    }
                }
            case .failure(let error):
                if let networkError = error as? WebService.NetworkError, networkError == .invalidRequest {
                    print("User is not in a carpool")
                } else {
                    print("Error fetching group data:", error)
                }
            }
        }

This is my fetchDailyEvents code from my EventViewModel:

  func fetchDailyEvents(forCarpoolID carpoolID: String, date: Date, completion: @escaping(Result<[Event], Error>) -> Void) {
        let dateFormatter = ISO8601DateFormatter()
        let dateString = dateFormatter.string(from: date)

        guard let apiURL = URL(string: "http://localhost/api/events/\(carpoolID)/\(dateString)") else {
            completion(.failure(NetworkError.invalidRequest))
            return
        }

        let task = URLSession.shared.dataTask(with: apiURL) { data, response, error in
            guard let data = data, error == nil else {
                completion(.failure(NetworkError.invalidResponse))
                return
            }

            let decoder = JSONDecoder()
            do {
                let events = try decoder.decode([Event].self, from: data)
                completion(.success(events))
            } catch {
                completion(.failure(error))
            }
        }
        task.resume()
    }

Finally, I will give you a snippet of my sign in function where it shows that I am saving it to user defaults:

 if result.user.isEmailVerified {
                    // User successfully signed in
                    // Navigate to the profile page or perform other actions
                    let carpoolID = UUID().uuidString
                    UserDefaults.standard.set(carpoolID, forKey: "carpoolID")
                    UserDefaults.standard.set(result.user.uid, forKey: "uid")
                    completion(true, "")
                } else {
                    // User's email is not verified, prompt them to verify their email
                    completion(false, "Please verify your email before signing in.")
                }

In my console, when I click on a day in my calendar page to show the events on that day it displays this: Fetching Events User ID not found in UserDefaults or invalid UUID string

I have verified that the event is being created and have lowered my code to make a minimalist reproducable example which is what I have given you. In my database, it shows the event exists with the correct information such as the date but the error persists. Any help is much appreciated thank you so much in advance!

0

Browse other questions tagged or ask your own question.