Skip to content
Advertisement

Loop from multiple airtable bases in a Next JS page

I think this more of a general async/await loop question, but I’m trying to do it within the bounds of an Airtable API request and within getStaticProps of Next.js so I thought that is important to share.

What I want to do is create an array of base IDs like ["appBaseId01", "appBaseId02", "appBaseId03"] and output the contents of a page. I have it working with 1 base, but am failing at getting it for multiple.

Below is the code for one static base, if anyone can help me grok how I’d want to loop over these. My gut says that I need to await each uniquely and then pop them into an array, but I’m not sure.

const records = await airtable
  .base("appBaseId01")("Case Overview Information")
  .select()
  .firstPage();

const details = records.map((detail) => {
  return {
    city: detail.get("City") || null,
    name: detail.get("Name") || null,
    state: detail.get("State") || null,
  };
});

return {
  props: {
    details,
  },
};

EDIT I’ve gotten closer to emulating it, but haven’t figured out how to loop the initial requests yet.

This yields me an array of arrays that I can at least work with, but it’s janky and unsustainable.

export async function getStaticProps() {
  const caseOneRecords = await setOverviewBase("appBaseId01")
    .select({})
    .firstPage();
  const caseTwoRecords = await setOverviewBase("appBaseId02")
    .select({})
    .firstPage();

  const cases = [];
  cases.push(minifyOverviewRecords(caseOneRecords));
  cases.push(minifyOverviewRecords(caseTwoRecords));

  return {
    props: {
      cases,
    },
  };
}

setOverviewBase is a helper that establishes the Airtable connection and sets the table name.

const setOverviewBase = (baseId) =>
  base.base(baseId)("Case Overview Information");

Advertisement

Answer

You can map the array of base IDs and await with Promise.all. Assuming you have getFirstPage and minifyOverviewRecords defined as below, you could do the following:

const getFirstPage = (baseId) => 
    airtable
        .base(baseId)("Case Overview Information")
        .select({})
        .firstPage();

const minifyOverviewRecords = (records) => 
    records.map((detail) => {
        return {
            city: detail.get("City") || null,
            name: detail.get("Name") || null,
            state: detail.get("State") || null,
        };
    });

export async function getStaticProps() {
    const cases = await Promise.all(
        ["appBaseId01", "appBaseId02", "appBaseId03"].map(async (baseId) => {
            const firstPage = await getFirstPage(baseId);
            return minifyOverviewRecords(firstPage);
        })
    );

    return {
        props: {
            cases
        }
    };
}
Advertisement