Hey everyone, I’m stuck on a problem with Next.js and Airtable. I’m trying to fetch data from several Airtable bases in my getStaticProps
function. Right now, I can get it working for one base, but I’m struggling to loop through multiple bases.
Here’s what I want to do: I have a list of base IDs like ["baseA", "baseB", "baseC"]
. I need to grab info from each base and combine it all together. My current code looks something like this:
async function getStaticProps() {
const myBase = airtable.base("baseA");
const data = await myBase("My Table").select().firstPage();
const cleanData = data.map(item => ({
town: item.get("Town"),
person: item.get("Person"),
region: item.get("Region")
}));
return { props: { cleanData } };
}
How can I modify this to work with multiple bases? Should I use Promise.all()
or is there a better way? Any help would be great!
hey there! i’ve been thru this too. using Promise.all() is a solid approach - just map over your base ids, get each base’s data, then merge everything. for example:
const allData = await Promise.all(bases.map(id => airtable.base(id)('My Table').select().firstPage()));
hope it helps!
I’ve encountered a similar challenge in my projects. One effective approach is to utilize Promise.all() combined with async/await. Here’s a solution that should work:
async function getStaticProps() {
const baseIds = ['baseA', 'baseB', 'baseC'];
const allData = await Promise.all(
baseIds.map(async (baseId) => {
const base = airtable.base(baseId);
const data = await base('My Table').select().firstPage();
return data.map(item => ({
town: item.get('Town'),
person: item.get('Person'),
region: item.get('Region')
}));
})
);
const cleanData = allData.flat();
return { props: { cleanData } };
}
This method efficiently fetches data from multiple bases concurrently, improving performance. Remember to handle potential errors appropriately in a production environment.
I’ve found that integrating multiple Airtable bases in a Next.js project can be simplified by reconsidering the approach. Instead of fetching data from each base separately with Promise.all, a more efficient solution is to create a single master base that syncs data from your other bases using Airtable’s Sync feature. This eliminates the need to loop through several bases in your getStaticProps function and reduces the number of API calls, thereby simplifying your code. Although this method may not provide real-time data, it works very well when managing large datasets and streamlines the overall integration process.