From 57617eff34b771421e8bd8cc1697419e1d7701c8 Mon Sep 17 00:00:00 2001 From: sosokker Date: Mon, 13 May 2024 15:24:29 +0700 Subject: [PATCH] Add action pie chart --- frontend/src/components/Charts/PieChart.tsx | 130 +++++++------------- frontend/src/types/action.ts | 4 + 2 files changed, 48 insertions(+), 86 deletions(-) create mode 100644 frontend/src/types/action.ts diff --git a/frontend/src/components/Charts/PieChart.tsx b/frontend/src/components/Charts/PieChart.tsx index afb6eff..c60fab7 100644 --- a/frontend/src/components/Charts/PieChart.tsx +++ b/frontend/src/components/Charts/PieChart.tsx @@ -1,9 +1,11 @@ import { ApexOptions } from 'apexcharts'; -import React, { useState } from 'react'; +import React, { useState, useEffect } from 'react'; import ReactApexChart from 'react-apexcharts'; -interface ChartThreeState { - series: number[]; +interface ChartData { + action: string; + count: number; + percentage: number; } const options: ApexOptions = { @@ -12,7 +14,7 @@ const options: ApexOptions = { type: 'donut', }, colors: ['#3C50E0', '#6577F3', '#8FD0EF', '#0FADCF'], - labels: ['Desktop', 'Tablet', 'Mobile', 'Unknown'], + labels: ['Sitting', 'Walking', 'Standing', 'Unknown'], legend: { show: false, position: 'bottom', @@ -50,111 +52,67 @@ const options: ApexOptions = { }; const PieChart: React.FC = () => { - const [state, setState] = useState({ - series: [65, 34, 12, 56], - }); + const [chartData, setChartData] = useState([]); - const handleReset = () => { - setState((prevState) => ({ - ...prevState, - series: [65, 34, 12, 56], - })); + useEffect(() => { + fetchData(); + }, []); + + const fetchData = async () => { + try { + const response = await fetch('http://127.0.0.1:8000/api/v1/action/week'); + const data: ActionData[] = await response.json(); + + const actionCounts: { [key: string]: number } = {}; + data.forEach((item) => { + actionCounts[item.action] = (actionCounts[item.action] || 0) + 1; + }); + + const totalCount = data.length; + const chartData = Object.keys(actionCounts).map((action) => ({ + action, + count: actionCounts[action], + percentage: (actionCounts[action] / totalCount) * 100, + })); + + setChartData(chartData); + } catch (error) { + console.error('Error fetching data:', error); + } }; - handleReset; return (
- Visitors Analytics + Action Analysis
-
-
- - - - - - - -
-
item.count)} type="donut" />
-
-
- -

- Desktop - 65% -

+ {chartData.map((item, index) => ( +
+
+ +

+ {item.action} + {item.count} times +

+
-
-
-
- -

- Tablet - 34% -

-
-
-
-
- -

- Mobile - 45% -

-
-
-
-
- -

- Unknown - 12% -

-
-
+ ))}
); diff --git a/frontend/src/types/action.ts b/frontend/src/types/action.ts new file mode 100644 index 0000000..764555c --- /dev/null +++ b/frontend/src/types/action.ts @@ -0,0 +1,4 @@ +interface ActionData { + timestamp: string; + action: string; +}