forked from PinSpace-Org/GistPin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSentimentTrend.ts
More file actions
57 lines (48 loc) 路 1.66 KB
/
Copy pathuseSentimentTrend.ts
File metadata and controls
57 lines (48 loc) 路 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
'use client';
import { useState, useEffect, useCallback } from 'react';
export type SentimentLabel = 'positive' | 'neutral' | 'negative';
export interface SentimentDataPoint {
date: string;
positive: number;
neutral: number;
negative: number;
total: number;
}
export interface SentimentSummary {
overallScore: number;
totalMentions: number;
positivePercentage: number;
negativePercentage: number;
trend: 'improving' | 'declining' | 'stable';
}
interface UseSentimentTrendOptions {
period?: '7d' | '30d' | '90d';
refreshInterval?: number;
}
export function useSentimentTrend(options: UseSentimentTrendOptions = {}) {
const { period = '30d', refreshInterval = 300000 } = options;
const [data, setData] = useState<SentimentDataPoint[]>([]);
const [summary, setSummary] = useState<SentimentSummary | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const fetchSentiment = useCallback(async () => {
try {
setLoading(true);
const res = await fetch(`/api/analytics/sentiment?period=${period}`);
if (!res.ok) throw new Error('Failed to fetch sentiment data');
const json = await res.json();
setData(json.data);
setSummary(json.summary);
} catch (err) {
setError(err instanceof Error ? err.message : 'Unknown error');
} finally {
setLoading(false);
}
}, [period]);
useEffect(() => {
fetchSentiment();
const interval = setInterval(fetchSentiment, refreshInterval);
return () => clearInterval(interval);
}, [fetchSentiment, refreshInterval]);
return { data, summary, loading, error, refetch: fetchSentiment };
}