import React, {createContext, PropsWithChildren, useContext, useEffect, useState} from "react" import {timeTracker, toDo} from "../utilities/types" import useAxiosTools from "./AxiosTools" const TrackerContext = createContext(undefined) interface TrackerProps { currentTimeTracker: timeTracker|null, startTrackToDo: (toDo: toDo) => void, stopCurrentTimeTrack: () => void, } export const TrackerProvider = ({children}: PropsWithChildren) => { const [currentTimeTracker, setCurrentTimeTracker] = useState(null) const {axiosGet, axiosPost, axiosDelete} = useAxiosTools() useEffect(() => { fetchCurrentTimeTracker() }, []) const fetchCurrentTimeTracker = async () => { try { const res = await axiosGet(`/api/time-trackers/user`) setCurrentTimeTracker(res.data) } catch (error) { console.error(error) } } const startTrackToDo = async (toDo: toDo) => { try { const res = await axiosPost('/api/time-trackers', {todo_id: toDo.id}) setCurrentTimeTracker(res.data) } catch (error) { console.error(error) } } const stopCurrentTimeTrack = async () => { try { await axiosDelete(`/api/time-trackers/user`) setCurrentTimeTracker(null) } catch (error) { console.error(error) } } return {children} } const useTracker = () => { const context = useContext(TrackerContext) if (context === undefined) { throw new Error('Add TrackerProvider to use AuthUserContext') } return context } export default useTracker