Blog>
Snippets

Normalizing Data for React Charts

Show how to transform and normalize a dataset from an API for compatibility with TanStack React Charts, ensuring data is in the correct format for visualization.
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => normalizeData(data))
  .then(normalizedData => {
    // Use this normalized data with TanStack React Charts
  });
This snippet fetches data from an API and then transforms the returned JSON data using the normalizeData function (defined next). The normalized data is then ready to be used with TanStack React Charts.
function normalizeData(data) {
  return data.map(item => ({
    /* Assuming the API returns data with 'date' and 'value' fields */
    x: item.date, // mapping 'date' to 'x'
    y: item.value // mapping 'value' to 'y'
  }));
}
The normalizeData function takes the raw data array from the API and maps it to a new array where each object has 'x' and 'y' properties. This format is compatible with many types of charts in TanStack React Charts, such as line or scatter charts.