import { getDatabase, ref, get } from "firebase/database";
import { useEffect, useState } from "react";
const database = getDatabase();
/**
* The function fetches data of a specific type from a Firebase Realtime Database and returns it as an
* array of objects with IDs included.
* @param pointType - The `pointType` parameter in the `fetchPoints` function is used to specify the
* type of points you want to fetch from the database. It is used to construct the path to the data in
* the database by appending it to the base path `newsuggestions/`. This allows you to retrieve
* specific
* @returns The `fetchPoints` function returns an array of objects with IDs included. If data is found
* at the specified path, it converts the object of objects to an array of objects with IDs included
* and returns that array. If no data is found at the path, it logs a message and returns an empty
* array. If an error occurs during the data retrieval process, it logs the error and propagates it
*/
export async function fetchPoints(pointType) {
const path = `newsuggestions/${pointType}`;
const dataRef = ref(database, path);
try {
const snapshot = await get(dataRef);
if (snapshot.exists()) {
const data = snapshot.val();
// Convert the object of objects to an array of objects with IDs included
const dataArray = Object.entries(data).map(([id, value]) => ({
id,
...value,
}));
return dataArray;
} else {
console.log(`No data found at path: ${path}`);
return []; // Return an empty array if no data is found
}
} catch (error) {
console.error(`Error retrieving data from path ${path}:`, error);
throw error; // Propagate the error to the caller
}
}