Blog>
Snippets

Structuring Data for TanStack React Charts

Demonstrate how to correctly structure a dataset for use with TanStack React Charts, including converting date strings to Date objects for a time series graph.
const rawData = [
  { date: '2023-01-01', value: 10 },
  { date: '2023-01-02', value: 15 },
  { date: '2023-01-03', value: 7 }
];
Defines the raw data array with dates represented as strings and associated values.
const structuredData = rawData.map(dataPoint => ({
  ...dataPoint,
  date: new Date(dataPoint.date)
}));
Converts each date string in the raw data into a JavaScript Date object, creating a new data array that is structured correctly for TanStack React Charts.
const chartData = {
  labels: structuredData.map(data => data.date),
  datasets: [{
    label: 'Dataset 1',
    data: structuredData.map(data => data.value)
  }]
};
Prepares the final data structure for the chart, including labels extracted from the date and values from the data points.