friendsNotificationsStore.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233
  1. import { fetchFriendsNotification } from '@api/friends';
  2. import { storage, StoreType } from 'src/storage';
  3. import { create } from 'zustand';
  4. interface FriendsNotificationState {
  5. isNotificationActive: number;
  6. setIsNotificationActive: (active: number) => void;
  7. updateNotificationStatus: () => Promise<void>;
  8. }
  9. export const useFriendsNotificationsStore = create<FriendsNotificationState>((set) => ({
  10. isNotificationActive: (storage.get('friendsNotification', StoreType.NUMBER) as number) ?? 0,
  11. setIsNotificationActive: (active: number) => set({ isNotificationActive: active }),
  12. updateNotificationStatus: async () => {
  13. const token = storage.get('token', StoreType.STRING);
  14. if (token) {
  15. try {
  16. const data = await fetchFriendsNotification(token as string);
  17. const count = data && data.count;
  18. if (typeof count === 'number') {
  19. set({ isNotificationActive: count });
  20. storage.set('friendsNotification', count);
  21. }
  22. } catch (error) {
  23. console.error('Failed to fetch friends notification status', error);
  24. }
  25. } else {
  26. set({ isNotificationActive: 0 });
  27. storage.set('friendsNotification', 0);
  28. }
  29. }
  30. }));