Converting Airtable record data to JSON format in React

I’m working on a React project in CodeSandbox and need help turning my Airtable records into a JSON file. I’ve created a function that retrieves all the records but I can only see the values printed in the console. Here’s my current implementation:

function fetchTableData(tableName) {
  let dataArray = []
  base(tableName).select().all()
    .then(function(entries) {
      entries.forEach(entry => {
        dataArray.push(entry._rawJson.fields)
      })
      // console.log(dataArray) shows ([Object, ...])
    })
  // return dataArray doesn't work
}

How can I modify this function so it returns dataArray as a JSON object? Any ideas would be appreciated!

hey mia, try using JSON.stringify on ur dataArray before returning it. like this:

return JSON.stringify(dataArray);

that should give u a JSON string u can use. also, make sure ur function is async and u await the base.select().all() call. hope this helps!

The issue you’re facing is related to asynchronous operations. Your function is returning before the data is fetched. To resolve this, you should return a Promise from your function. Here’s a modified version that should work:

async function fetchTableData(tableName) {
try {
const entries = await base(tableName).select().all();
const dataArray = entries.map(entry => entry._rawJson.fields);
return JSON.stringify(dataArray);
} catch (error) {
console.error(‘Error fetching data:’, error);
return null;
}
}

You can then use this function like:

fetchTableData(‘YourTableName’).then(jsonData => {
if (jsonData) {
const parsedData = JSON.parse(jsonData);
// Use parsedData as needed
}
});

This approach ensures the data is fully fetched before returning, and provides error handling.

I’ve dealt with similar Airtable-to-JSON issues before. Your approach is close, but you’re running into async problems. Here’s what worked for me:

async function fetchTableData(tableName) {
  try {
    const entries = await base(tableName).select().all();
    const dataArray = entries.map(entry => entry._rawJson.fields);
    return dataArray; // No need to stringify here
  } catch (error) {
    console.error('Fetch failed:', error);
    return [];
  }
}

// Usage
fetchTableData('YourTable').then(data => {
  const jsonData = JSON.stringify(data);
  // Use jsonData as needed
});

This keeps your data as an array of objects until you actually need it as JSON. It’s more flexible this way. Also, using map() instead of forEach() with push() is generally cleaner and faster. Hope this helps!