CoreControl/hooks/useNotifications.ts
2025-05-25 00:32:16 +02:00

53 lines
1.5 KiB
TypeScript

import { useState, useEffect, useCallback } from "react";
import axios from "axios";
const useNotifications = () => {
const [notifications, setNotifications] = useState([]);
const [loading, setLoading] = useState(false);
const loadNotifications = useCallback(() => {
setLoading(true);
axios.get('/api/notifications/get').then((response) => {
setNotifications(response.data.notifications);
setLoading(false);
});
}, []);
useEffect(() => {
loadNotifications();
}, [loadNotifications]);
const addNotification = (name: string, type: string, config: string): Promise<string> | string => {
if(name.length < 3) {
return 'Notification name must be at least 3 characters long';
}
return axios.post('/api/notifications/add', { name, type, config })
.then((response) => {
return response.data.notification;
})
.catch(err => {
throw err.response?.data?.error || 'An error occurred';
});
};
const deleteNotification = (notificationId: number) => {
axios.delete('/api/notifications/delete', { params: { notificationId } })
.then(() => {
return "Notification deleted successfully";
})
.catch(err => {
throw err.response?.data?.error || 'An error occurred';
});
}
return {
notifications,
loading,
addNotification,
deleteNotification,
loadNotifications
};
}
export default useNotifications;