Fetching and displaying Airtable data with JavaScript

I’m stuck trying to show questions from Airtable on my webpage using JavaScript. I’ve set up a fetch request to get the data, but I think my variables aren’t being filled with the questions. Here’s what I’ve tried:

const fetchQuestions = () => {
  const apiKey = 'your_api_key_here';
  const baseId = 'your_base_id_here';
  const tableId = 'your_table_id_here';

  fetch(`https://api.airtable.com/v0/${baseId}/${tableId}`, {
    headers: { Authorization: `Bearer ${apiKey}` }
  })
  .then(response => response.json())
  .then(data => {
    const questionSet = data.records.find(record => record.fields.set_id === 1);
    if (questionSet) {
      for (let i = 1; i <= 10; i++) {
        const questionElement = document.getElementById(`question${i}`);
        questionElement.textContent = questionSet.fields[`Question${i}`];
      }
    }
  })
  .catch(error => console.error('Error:', error));
};

fetchQuestions();

I’m not sure why the questions aren’t showing up on the page. Any ideas what I’m doing wrong? Thanks for any help!

I’ve dealt with Airtable integration before, and one thing that often trips people up is asynchronous loading. Your code looks solid, but you might want to ensure the DOM is fully loaded before executing fetchQuestions(). Try wrapping your function call in a DOMContentLoaded event listener:

document.addEventListener('DOMContentLoaded', () => {
  fetchQuestions();
});

Also, consider adding some error handling within your fetch chain. Sometimes, Airtable returns successful responses even when there’s no data. You could check if data.records is empty before proceeding. Lastly, make sure your API key is active and has the correct permissions. These small tweaks might just solve your issue!

hey jumpinrabbit, check that your html id’s match your airtable field names exactly. try logging the fetched data to see what u get. hope that helps!

I encountered a similar issue when working with Airtable’s API. One thing to consider is the structure of your Airtable base. Ensure that your ‘set_id’ field is actually named that way and contains numeric values. Also, double-check that your field names in Airtable match exactly with what you’re trying to access in your code (e.g., ‘Question1’, ‘Question2’, etc.). Another potential issue could be CORS-related. If you’re running this locally, you might need to set up a proxy server or use Airtable’s JavaScript library instead of the fetch API. Lastly, make sure your API key has the necessary permissions to read from the specified base and table.