How to Display API Data in Line Charts Using react-chartjs-2

If we’re working with the Quickbase API and want to visualize the returned data using react-chartjs-2, we’re in the right place. One common use case is to display numerical job-related fields (like costs, durations, etc.) over time or by project/job title using a line chart.

Below, we’ll walk through:

  • How to correctly fetch and format Quickbase API data
  • How to transform that data for a line chart</li
  • How to display it dynamically using Chart.js (through react-chartjs-2)

Class component:

Copy to clipboard
import React, { Component } from 'react';
import { Line } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  LineElement,
  CategoryScale,
  LinearScale,
  PointElement,
  Tooltip,
  Legend,
} from 'chart.js';
ChartJS.register(
  LineElement,
  CategoryScale,
  LinearScale,
  PointElement,
  Tooltip,
  Legend
);
const headers = {
  'QB-Realm-Hostname': 'YOUR_REALM.quickbase.com',
  'User-Agent': 'FileService_Integration_V2.1',
  'Authorization': 'QB-USER-TOKEN YOUR_TOKEN',
  'Content-Type': 'application/json',
};
class TotalLineChart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      chartData: null,
    };
  }
  componentDidMount() {
    this.fetchData();
  }
  fetchData = () => {
    const body = {
      from: 'bpz99ram7',
      select: [3, 6, 80], // 3 = Job ID, 6 = Title, 80 = Cost (example)
      where: "{40.CT. 'In Progress'}", // Filter for jobs in progress
      sortBy: [{ fieldId: 6, order: 'ASC' }],
      options: { skip: 0, top: 0 },
    };

    fetch('https://api.quickbase.com/v1/records/query', {
      method: 'POST',
      headers: headers,
      body: JSON.stringify(body),
    })
      .then((response) => response.json())
      .then((data) => this.prepareChartData(data))
      .catch((error) => console.error('API fetch error:', error));
  };

  prepareChartData = (apiResponse) => {
    const records = apiResponse.data;

    // Extract labels (e.g., Job Titles)
    const labels = records.map((record) => record['6']?.value || 'No Title');

    // Extract data points (e.g., Job Costs)
    const dataPoints = records.map((record) => record['80']?.value || 0);

    const chartData = {
      labels,
      datasets: [
        {
          label: 'Job Cost',
          data: dataPoints,
          fill: false,
          borderColor: '#00498D',
          tension: 0.2,
        },
      ],
    };

    this.setState({ chartData });
  };
  render() {
    const { chartData } = this.state;

    if (!chartData) return <div>Loading chart...</div>;

    const options = {
      responsive: true,
      plugins: {
        legend: { position: 'top' },
      },
      scales: {
        y: {
          beginAtZero: true,
        },
      },
    };

    return (
      <div style={{ width: '90%', margin: '0 auto' }}>
        <h2>Line Chart - Job Cost by Title</h2>
        <Line data={chartData} options={options} />
      </div>
    );
  }
}
export default TotalLineChart;

Here is also a functional component example: (Code snippet compatible for React version 18+)

Copy to clipboard
import React, { useEffect, useState } from 'react';
import { Line } from 'react-chartjs-2';
import {
  Chart as ChartJS,
  LineElement,
  CategoryScale,
  LinearScale,
  PointElement,
  Tooltip,
  Legend,
} from 'chart.js';

ChartJS.register(
  LineElement,
  CategoryScale,
  LinearScale,
  PointElement,
  Tooltip,
  Legend
);

const headers = {
  'QB-Realm-Hostname': 'YOUR_REALM.quickbase.com',
  'User-Agent': 'FileService_Integration_V2.1',
  'Authorization': 'QB-USER-TOKEN YOUR_TOKEN',
  'Content-Type': 'application/json',
};

const TotalLineChart = () => {
  const [chartData, setChartData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const body = {
        from: 'bpz99ram7',
        select: [3, 6, 80], // 3 = Job ID, 6 = Title, 80 = Cost (example)
        where: "{40.CT. 'In Progress'}",
        sortBy: [{ fieldId: 6, order: 'ASC' }],
        options: { skip: 0, top: 0 },
      };

      try {
        const response = await fetch('https://api.quickbase.com/v1/records/query', {
          method: 'POST',
          headers,
          body: JSON.stringify(body),
        });

        const data = await response.json();
        prepareChartData(data);
      } catch (error) {
        console.error('API fetch error:', error);
      }
    };

    const prepareChartData = (apiResponse) => {
      const records = apiResponse.data;
      const labels = records.map((record) => record['6']?.value || 'No Title');
      const dataPoints = records.map((record) => record['80']?.value || 0);

      setChartData({
        labels,
        datasets: [
          {
            label: 'Job Cost',
            data: dataPoints,
            fill: false,
            borderColor: '#00498D',
            tension: 0.2,
          },
        ],
      });
    };

    fetchData();
  }, []);

  const options = {
    responsive: true,
    plugins: {
      legend: { position: 'top' },
    },
    scales: {
      y: {
        beginAtZero: true,
      },
    },
  };

  return (
    <div style="{{" width:="" '90%',="" margin:="" '0="" auto'="" }}="">
      <h2>Line Chart - Job Cost by Title</h2>
      {chartData ? (
        <line data="{chartData}" options="{options}">
      ) : (
        <div>Loading chart...</div>
      )}
    </line></div>
  );
};

export default TotalLineChart;

What’s Happening Here?

API Call: Fetches job records filtered by status = “In Progress”.

  • 6: Title or job name.
  • 80: Example field representing job cost.

Transforming Data: We map the response to extract an array of labels and values for Chart.js.

Line Chart Display: Each job title is plotted with its corresponding cost.

This post showed how to:

  • Connect to Quickbase API,
  • Parse the response,
  • Format it for a line chart using react-chartjs-2,
  • Fix common issues with rendering chart data.

Need Help With React js Development?

Work with our skilled React developers to accelerate your project and boost its performance.

Support On Demand!