Reading data from Json API, processing it and displaying on the page is one of the most popular solutions on the web.
Can we do this with pure Typescript and frontend only? Let’s ask AI….
Then we need to compile ts into javascript, create js code snippet and make sure our && is not replaced with & (we may need to rewrite our code) and it works.
See chart below….
// Function to fetch data from the external API using Fetch API
async function fetchData(apiUrl: string): Promise<CompanyData[]> {
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`API request failed with status: ${response.status}`);
}
const jsonData: CompanyData[] = await response.json() as CompanyData[];
return jsonData;
} catch (error) {
console.error("Error fetching data:", error);
throw error; // Re-throw the error for handling in the calling code
}
}
// Function to populate the dropdown menu
async function populateDropdown(jsonData: CompanyData[]) {
const uniqueCompanies = new Set<string>();
jsonData.forEach((node) => uniqueCompanies.add(node.company));
const uniqueCompaniesArray = Array.from(uniqueCompanies).sort();
const dropdown = document.getElementById('companyDropdown') as HTMLSelectElement;
uniqueCompaniesArray.forEach((company) => {
const option = document.createElement('option');
option.value = company;
option.text = company;
dropdown.appendChild(option);
});
// Select the first company by default
dropdown.value = uniqueCompaniesArray[0];
// Update chart on dropdown change
dropdown.addEventListener('change', () => updateChart(jsonData));
}
// Function to update the bar chart based on selected company
function updateChart(jsonData) {
var dropdown = document.getElementById('companyDropdown');
var selectedCompany = dropdown.value;
var filteredData = jsonData.filter(function (node) { return node.company === selectedCompany; });
var retrievalDates = filteredData.map(function (node) { return getDate(node.retrievaldate); });
var jobCounts = filteredData.map(function (node) { return node.number_of_jobs; });
// Use Chart.js to create the bar chart (replace with your preferred library)
var canvas = document.getElementById('barChart');
var ctx = canvas.getContext('2d');
if (currentChart) {
currentChart.destroy();
}
var barChart = new Chart(ctx, {
type: 'bar',
data: {
labels: retrievalDates,
datasets: [{
label: 'Number of Jobs',
data: jobCounts,
backgroundColor: 'rgba(0, 35, 147, 0.8)',
borderColor: 'rgba(0, 35, 147, 1)',
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
currentChart = barChart;
}