Admin Helper
Documentation for getDashboardData Function
Overview
The getDashboardData function is an asynchronous function that retrieves dashboard data from a specified API endpoint. This function is designed to be used within the context of a React application, particularly for fetching and displaying administrative dashboard data.
Function Definition
import axios from "axios";
export const getDashboardData = async (token: string) => { try { const response = await axios.get( `${process.env.NEXT_PUBLIC_API_URL}/reports/all`, { headers: { Authorization: `Bearer ${token}`, }, } ); // Return data only if the response status is 200 if (response.status === 200) { return response.data; } else { console.error("Failed to fetch dashboard data", response.status); return null; } } catch (error) { console.error("Error fetching dashboard data:", error); return null; }};Parameters
- token (
string): The authentication token required to access the API. This token should be a valid JWT or another form of authentication token as expected by the API.
Returns
- Promise<Object | null>: The function returns a promise that resolves to the dashboard data object if the request is successful (status code 200). If the request fails or an error occurs, it returns
null.
How It Works
- Axios GET Request: The function makes a GET request to the
/reports/allendpoint of the API using theaxioslibrary. It includes the authentication token in the request headers. - Response Handling:
- If the response status is 200, it returns the response data.
- If the response status is not 200, it logs an error message and returns
null.
- Error Handling: If an error occurs during the request, it catches the error, logs an error message, and returns
null.
Usage Example
import { getDashboardData } from "./path-to-your-function";
const fetchDashboardData = async () => { const token = "your-auth-token"; // Replace with your actual token const data = await getDashboardData(token);
if (data) { console.log("Dashboard Data:", data); } else { console.log("Failed to fetch dashboard data"); }};
fetchDashboardData();In this example, the fetchDashboardData function demonstrates how to use the getDashboardData function. It fetches the dashboard data using a provided authentication token and logs the data to the console if the request is successful. If the request fails, it logs an error message indicating the failure.
Conclusion
The getDashboardData function is a utility for fetching dashboard data from a specified API endpoint. It handles authentication, response validation, and error logging, providing a reliable way to retrieve and use dashboard data in a React application.