You are currently viewing Creating a Dashboard with Axios and Chartjs

Creating a Dashboard with Axios and Chartjs

Creating a dashboard involves fetching and displaying data in a visual format, which can help users make informed decisions based on real-time information. Combining Axios, a promise-based HTTP client, with Chart.js, a popular JavaScript library for data visualization, enables developers to build dynamic and interactive dashboards with ease.

In this comprehensive guide, we will explore how to use Axios and Chart.js to create a dashboard. We will cover setting up Axios and Chart.js, creating a dashboard layout, fetching data, integrating data with Chart.js, updating charts dynamically, and handling errors and loading states. By the end of this article, you will have a robust understanding of how to build a dashboard using Axios and Chart.js.

Setting Up Axios in Your Project

Installing Axios

To get started with Axios, you need to install it in your project. This can be done easily using npm or yarn.

Using npm:

npm install axios

Using yarn:

yarn add axios

Basic Configuration

Once installed, you can configure Axios in your project by importing it and setting default parameters. Here is a basic setup:

import axios from 'axios';

// Create an Axios instance with default configuration
const apiClient = axios.create({
  baseURL: 'https://api.example.com',
  headers: {
    'Content-Type': 'application/json'
  }
});

export default apiClient;

This configuration ensures that all your Axios requests use the specified base URL and headers, simplifying your code and reducing redundancy.

Setting Up Chart.js

Installing Chart.js

To use Chart.js in your project, you need to install it. This can be done using npm or yarn.

Using npm:

npm install chart.js

Using yarn:

yarn add chart.js

Basic Configuration

Once installed, you can configure Chart.js in your project. Here is a basic setup:

import { Chart, registerables } from 'chart.js';

// Register the necessary components
Chart.register(...registerables);

export default Chart;

This setup registers the necessary Chart.js components, allowing you to create various types of charts.

Creating a Dashboard Layout

Introduction to Dashboard Layout

A dashboard layout typically consists of multiple sections or widgets that display different types of data. In this section, we will create a basic layout for our dashboard using React components.

Code Example: Setting Up the Layout

Here’s how to set up a basic dashboard layout in React:

import React from 'react';

const Dashboard = () => {

  return (
    <div className="dashboard">

      <h1>Dashboard</h1>

      <div className="charts">

        <div className="chart-container">
          <canvas id="chart1"></canvas>
        </div>

        <div className="chart-container">
          <canvas id="chart2"></canvas>
        </div>

      </div>

    </div>
  );
};

export default Dashboard;

In this example, we create a Dashboard component with a basic layout containing two chart containers. Each container includes a canvas element where the charts will be rendered.

Fetching Data with Axios

Introduction to Data Fetching

Fetching data from an API is a crucial part of building a dynamic dashboard. Axios simplifies this process by providing an easy-to-use interface for making HTTP requests.

Code Example: Making GET Requests with Axios

Here’s how to fetch data with Axios:

import React, { useEffect, useState } from 'react';
import apiClient from './apiClient';

const Dashboard = () => {

  const [data, setData] = useState([]);

  useEffect(() => {

    const fetchData = async () => {

      try {
        const response = await apiClient.get('/data-endpoint');
        setData(response.data);
      } catch (error) {
        console.error('Error fetching data:', error);
      }

    };

    fetchData();

  }, []);

  return (
    <div className="dashboard">

      <h1>Dashboard</h1>

      <div className="charts">

        <div className="chart-container">
          <canvas id="chart1"></canvas>
        </div>

        <div className="chart-container">
          <canvas id="chart2"></canvas>
        </div>

      </div>

    </div>
  );
};

export default Dashboard;

In this example, we use the useEffect hook to fetch data from the API when the component mounts. The data is stored in the data state variable and will be used to populate the charts.

Integrating Data with Chart.js

Introduction to Chart Integration

Integrating data with Chart.js involves creating chart instances and updating them with the fetched data. This provides a visual representation of the data on the dashboard.

Code Example: Rendering Charts with Fetched Data

Here’s how to render charts with fetched data:

import React, { useEffect, useState } from 'react';
import { Chart } from 'chart.js';
import apiClient from './apiClient';

const Dashboard = () => {

  const [data, setData] = useState([]);

  useEffect(() => {

    const fetchData = async () => {

      try {

        const response = await apiClient.get('/data-endpoint');
        setData(response.data);

        // Create chart instances
        const ctx1 = document.getElementById('chart1').getContext('2d');

        new Chart(ctx1, {
          type: 'line',
          data: {
            labels: response.data.labels,
            datasets: [{
              label: 'Dataset 1',
              data: response.data.values,
              backgroundColor: 'rgba(75, 192, 192, 0.2)',
              borderColor: 'rgba(75, 192, 192, 1)',
              borderWidth: 1
            }]
          }
        });

        const ctx2 = document.getElementById('chart2').getContext('2d');
        new Chart(ctx2, {
          type: 'bar',
          data: {
            labels: response.data.labels,
            datasets: [{
              label: 'Dataset 2',
              data: response.data.values,
              backgroundColor: 'rgba(153, 102, 255, 0.2)',
              borderColor: 'rgba(153, 102, 255, 1)',
              borderWidth: 1
            }]
          }
        });

      } catch (error) {
        console.error('Error fetching data:', error);
      }
    };

    fetchData();

  }, []);

  return (
    <div className="dashboard">

      <h1>Dashboard</h1>

      <div className="charts">

        <div className="chart-container">
          <canvas id="chart1"></canvas>
        </div>

        <div className="chart-container">
          <canvas id="chart2"></canvas>
        </div>

      </div>
    </div>
  );

};

export default Dashboard;

In this example, we create chart instances using Chart.js inside the fetchData function. The chart data is populated with the fetched data, and the charts are rendered in the corresponding canvas elements.

Updating Charts Dynamically

Introduction to Dynamic Updates

Updating charts dynamically involves fetching new data at regular intervals and updating the chart instances with the new data. This ensures that the dashboard displays the most up-to-date information.

Code Example: Updating Charts with New Data

Here’s how to update charts dynamically:

import React, { useEffect, useState } from 'react';
import { Chart } from 'chart.js';
import apiClient from './apiClient';

const Dashboard = () => {

  const [data, setData] = useState([]);
  let chart1, chart2;

  useEffect(() => {

    const fetchData = async () => {

      try {

        const response = await apiClient.get('/data-endpoint');
        setData(response.data);

        const ctx1 = document.getElementById('chart1').getContext('2d');

        chart1 = new Chart(ctx1, {
          type: 'line',
          data: {
            labels: response.data.labels,
            datasets: [{
              label: 'Dataset 1',
              data: response.data.values,
              backgroundColor: 'rgba(75, 192, 192, 0.2)',
              borderColor: 'rgba(75, 192, 192, 1)',
              borderWidth: 1
            }]
          }
        });

        const ctx2 = document.getElementById('chart2').getContext('2d');

        chart2 = new Chart(ctx2, {
          type: 'bar',
          data: {
            labels: response.data.labels,
            datasets: [{
              label: 'Dataset 2',
              data: response.data.values,
              backgroundColor: 'rgba(153, 102, 255, 0.2)',
              borderColor: 'rgba(153, 102, 255, 1)',
              borderWidth: 1
            }]
          }
        });

      } catch (error) {
        console.error('Error fetching data:', error);
      }

    };

    const updateData = async () => {

      try {

        const response = await apiClient.get('/data-endpoint');
        chart1.data.labels = response.data.labels;
        chart1.data.datasets[0].data = response.data.values;
        chart1.update();

        chart2.data.labels = response.data.labels;
        chart2.data.datasets[0].data = response.data.values;
        chart2.update();

      } catch (error) {
        console.error('Error updating data:', error);
      }

    };

    fetchData();

    const intervalId = setInterval(updateData, 60000); // Update every 60 seconds

    return () => clearInterval(intervalId);

  }, []);

  return (
    <div className="dashboard">

      <h1>Dashboard</h1>

      <div className="charts">

        <div className="chart-container">
          <canvas id="chart1"></canvas>
        </div>

        <div className="chart-container">
          <canvas id="chart2"></canvas>
        </div>

      </div>
    </div>

  );

};

export default Dashboard;

In this example, we define an updateData function that fetches new data and updates the chart instances. The setInterval function calls updateData every 60 seconds, ensuring that the charts display the most recent data.

Handling Errors and Loading States

Introduction to Error and Loading Management

Handling errors and loading states ensures that users are informed about the status of data fetching operations. Displaying appropriate messages and indicators improves the user experience.

Code Example: Managing Errors and Loading States

Here’s how to manage errors and loading states in the dashboard component:

import React, { useEffect, useState } from 'react';
import { Chart } from 'chart.js';
import apiClient from './apiClient';

const Dashboard = () => {

  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  let chart1, chart2;

  useEffect(() => {

    const fetchData = async () => {

      setLoading(true);
      setError(null);

      try {

        const response = await apiClient.get('/data-endpoint');
        setData(response.data);

        const ctx1 = document.getElementById('chart1').getContext('2d');

        chart1 = new Chart(ctx1, {
          type: 'line',
          data: {
            labels: response.data.labels,
            datasets: [{
              label: 'Dataset 1',
              data: response.data.values,
              backgroundColor: 'rgba(75, 192, 192, 0.2)',
              borderColor: 'rgba(75, 192, 192, 1)',
              borderWidth: 1
            }]
          }
        });

        const ctx2 = document.getElementById('chart2').getContext('2d');

        chart2 = new Chart(ctx2, {
          type: 'bar',
          data: {
            labels: response.data.labels,
            datasets: [{
              label: 'Dataset 2',
              data: response.data.values,
              backgroundColor: 'rgba(153, 102, 255, 0.2)',
              borderColor: 'rgba(153, 102, 255, 1)',
              borderWidth: 1
            }]
          }
        });

      } catch (error) {
        setError('Error fetching data');
        console.error('Error fetching data:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();

    const updateData = async () => {

      try {

        const response = await apiClient.get('/data-endpoint');
        chart1.data.labels = response.data.labels;
        chart1.data.datasets[0].data = response.data.values;
        chart1.update();

        chart2.data.labels = response.data.labels;
        chart2.data.datasets[0].data = response.data.values;
        chart2.update();

      } catch (error) {
        console.error('Error updating data:', error);
      }

    };

    const intervalId = setInterval(updateData, 60000); // Update every 60 seconds

    return () => clearInterval(intervalId);

  }, []);

  return (
    <div className="dashboard">

      <h1>Dashboard</h1>

      {loading && <p>Loading...</p>}
      {error && <p style={{ color: 'red' }}>{error}</p>}

      <div className="charts">

        <div className="chart-container">
          <canvas id="chart1"></canvas>
        </div>

        <div className="chart-container">
          <canvas id="chart2"></canvas>
        </div>

      </div>

    </div>
  );
};

export default Dashboard;

In this example, we manage loading states and errors using the loading and error state variables. We display a loading message while data is being fetched and an error message if an error occurs.

Conclusion

In this article, we explored how to use Axios and Chart.js to create a dynamic dashboard. We covered setting up Axios and Chart.js, creating a dashboard layout, fetching data, integrating data with Chart.js, updating charts dynamically, and handling errors and loading states. These steps ensure that your dashboard is responsive, interactive, and user-friendly.

The examples and concepts discussed in this article provide a solid foundation for creating dynamic dashboards. I encourage you to experiment with these techniques, adapting them to your specific use cases and enhancing the functionality and interactivity of your dashboards.

Additional Resources

To continue your learning journey with Axios, Chart.js, and dashboards, here are some additional resources:

  1. Axios Documentation: The official documentation offers detailed information and usage examples. Axios Documentation
  2. Chart.js Documentation: Comprehensive guide on using Chart.js for data visualization. Chart.js Documentation
  3. React Documentation: Comprehensive guide on building user interfaces with React. React Documentation
  4. JavaScript Promises: Learn more about promises and asynchronous programming in JavaScript. MDN Web Docs – Promises
  5. Handling Errors in JavaScript: Comprehensive guide on error handling in JavaScript. MDN Web Docs – Error Handling

By utilizing these resources, you can deepen your understanding of Axios and Chart.js and enhance your ability to create powerful and interactive dashboards in your web applications.

Leave a Reply