Search code examples
javascriptreactjsreact-hooksairtable

How to I select the records only when I click on the button?


I am using Airtable blocks to create an extension. I have a button that, when pressed, should retrieve the records. However, I am not able to get it to run when the button is clicked...only when the button is loaded. I only want it to run when clicked since I have a lot of tables and loading all the records from all the tables at once could be overkill. How do I get it to run only when I press the button? The error I get is Error: Invalid hook call. Hooks can only be called inside of the body of a function component. Without the

 import React, { useState, useEffect } from "react";
 import { useBase, useRecords, Button } from "@airtable/blocks/ui";
 
 function getRecords(Item) {
   const base = useBase();
   const table = base.getTableIfExists(Item.table);
   return useRecords(table);
 }
 
 export default function RunButton({ Item }) {
   // This works but will potentially load a LOT of data
   const records = getRecords(Item);
   records.map((record) => {
     console.log(record.id);
   });
 
   // This errors
   function onClick() {
     const records = getRecords(Item);
     records.map((record) => {
       console.log(record.id);
     });
   }
 
   return (
     <Button size="small" icon="play" onClick={onClick}>
       Run
     </Button>
   );
 }

Solution

  • The error occurs because hooks like useBase and useRecords can only be called at top level of function component not inside other function or event handlers like onClick.You should call then at top of your RunButton component and use like this:

    const base = useBase();
      const table = base.getTableIfExists(Item.table);
    
      async function onClick() {
        const records = await table.selectRecordsAsync();
        records.records.map(record => {
          console.log(record.id);
        });
      }