I’m working on a React project and need help with processing Airtable data. I have a function that fetches records from my Airtable base, but I’m having trouble returning the data properly.
The function successfully retrieves all records and I can see them in the console, but when I try to return the array, it comes back empty. Here’s what I’m working with:
function fetchTableData(tableName) {
var dataArray = []
airtableBase(tableName).select().all()
.then(
function (recordSet) {
for (let index = 0; index < recordSet.length; index++)
dataArray.push(recordSet[index]._rawJson.fields)
// console.log(dataArray) shows the data correctly
});
// return dataArray // this returns empty array
}
How can I properly return this data and convert it to JSON format? The async nature seems to be causing issues with the return statement.
Yeah, you’re hitting a classic async issue. Your function returns the empty array before Airtable actually fetches the data. I ran into this exact thing when I started using Airtable with React. Here’s the fix - make your function async and await the promise:
When you call this function, you’ll need to use await or .then() since it returns a promise now. The data’s already JSON once you grab the fields, so no extra conversion needed. Using map() instead of a for loop keeps things cleaner too.
Had the exact same issue when I first added Airtable to my React app. Your return statement runs immediately, but the .then() callback happens later. The other answers work great, but here’s a callback approach if you don’t want to mess with promises in your component:
I found this way easier to wrap my head around when starting out. Airtable fields are already JSON, so no extra conversion needed. Just handle the empty state in your component while data loads.