Bla

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

// src/context/RideContext.

jsx
import { createContext, useContext, useState } from "react";
import { db, realTimeDb } from "../services/firebase";
import { collection, addDoc, getDocs } from "firebase/firestore";
import { ref, push } from "firebase/database";

const RideContext = createContext();

export function RideProvider({ children }) {


const [rides, setRides] = useState([]);

// Publish a ride to Firestore


const publishRide = async (rideDetails) => {
try {
const docRef = await addDoc(collection(db, "rides"), rideDetails);
console.log("Ride published with ID: ", docRef.id);
} catch (error) {
console.error("Error adding document: ", error);
}
};

// Send a notification to the Realtime Database


const sendNotification = (driverId, notification) => {
push(ref(realTimeDb, `notifications/${driverId}`), notification);
};

// Fetch rides from Firestore


const fetchRides = async () => {
try {
const querySnapshot = await getDocs(collection(db, "rides"));
const fetchedRides = querySnapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}));
setRides(fetchedRides);
} catch (error) {
console.error("Error fetching rides: ", error);
}
};

return (
<RideContext.Provider value={{ rides, publishRide, sendNotification, fetchRides
}}>
{children}
</RideContext.Provider>
);
}

export const useRides = () => useContext(RideContext);

You might also like