Introduction
Open-source APIs provide a great way to integrate useful data into your projects. WakaTime is one such API that helps developers track their coding activity across different projects and languages. In this article, we'll explore how to fetch coding stats from WakaTime and use them in a React application to visualize coding time using Chart.js.
Step 1: Get Your WakaTime API Key
To access WakaTime's API, you need an API key. Follow these steps to get it:
- Go to WakaTime.
- Sign in and navigate to your Account Settings.
- Under API Key, copy the key.
Step 2: Fetch Data from WakaTime API
WakaTime provides various endpoints, but for this example, we will use the /users/current/stats/last_7_days
endpoint to get coding stats for the past week.
Example API Request
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://wakatime.com/api/v1/users/current/stats/last_7_days
Sample Response
{
"stats": {
"data": {
"languages": [
{ "name": "JavaScript", "total_seconds": 14400 },
{ "name": "Python", "total_seconds": 7200 }
],
"projects": [
{ "name": "Portfolio Website", "total_seconds": 10800 },
{ "name": "To-Do App", "total_seconds": 3600 }
]
}
}
}
Step 3: Fetch and Display WakaTime Stats in a React App
Now, let’s create a Statistics.tsx
component in a React app to fetch and display this data using Chart.js.
Install Dependencies
Run the following command to install Axios and Chart.js:
npm install axios chart.js react-chartjs-2
Create Statistics.tsx
import React, { useEffect, useState } from "react";
import axios from "axios";
import { Bar } from "react-chartjs-2";
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
BarElement,
Title,
Tooltip,
Legend,
} from "chart.js";
// Register Chart.js components
ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend);
const Statistics: React.FC = () => {
const [chartData, setChartData] = useState({ labels: [], datasets: [] });
const [projects, setProjects] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get("http://localhost:10000/api/stats");
console.log("Raw API Response:", response.data);
const apiData = response.data?.stats?.data;
if (!apiData || !apiData.languages || !apiData.projects) {
console.warn("⚠️ No valid data found in API response.");
return;
}
setChartData({
labels: apiData.languages.map((lang) => lang.name),
datasets: [
{
label: "Hours Spent",
data: apiData.languages.map((lang) => lang.total_seconds / 3600),
backgroundColor: "rgba(54, 162, 235, 0.6)",
},
],
});
setProjects(apiData.projects.map((project) => ({
name: project.name,
timeSpent: `${Math.floor(project.total_seconds / 3600)} hrs`,
link: `/projects/${encodeURIComponent(project.name)}`,
})));
} catch (error) {
console.error("❌ Error fetching WakaTime data:", error);
}
};
fetchData();
}, []);
return (
<div className="p-6">
<h2 className="text-3xl font-bold">Coding Stats (Last 7 Days)</h2>
<div>
<Bar data={chartData} options={{ responsive: true }} />
</div>
<h3 className="text-2xl">Projects</h3>
{projects.length > 0 ? (
projects.map((project, index) => (
<a key={index} href={project.link} className="block p-2">
{project.name} - {project.timeSpent}
</a>
))
) : (
<p>No project data available.</p>
)}
</div>
);
};
export default Statistics;
Step 4: Run Your React App
Make sure your API server is running and then start your React app:
npm start
Go to your browser and check the /statistics
route to see the visualization.
Conclusion
By integrating WakaTime’s open-source API, you can track your coding activity, visualize your most-used languages, and monitor project time—all inside your own custom dashboard! 🚀
Top comments (0)