简体   繁体   中英

Small API queries in Gatsby with GraphQL and React

I'm trying to import items from Airtable to Gatsby. My table has close to 800 records. It's not a heavy load per se, but I would like to render a few items at a time, with a "more" button to call the next batch. This is not obvious in Gatsby, since it seems to be directed to queries of smaller databases.

What is the best course of action here? I've tried adding a function to the button that updates the startIndex and endIndex variables, but the page won't render again, and simply attaching a forceUpdate to the Button will not work. I've also tried moving the items list to a component but placing the button next to it always throws an error. Should I store the query in a const first? Has anyone attempted this before?


import { graphql } from "gatsby"

export const query = graphql`
  {
    allAirtable(sort: {order: ASC, fields: id}, limit: 100) {
      nodes {
        id
        data {
          Name
          Area
          Year
        }
      }
    }
  }
 ` 

let startIndex = 0;
let endIndex = 10;

const IndexPage = ({ data }) => {

  return(
  <div>
    <h1>Item list</h1>
    <p>Page count: {data.allAirtable.pageInfo.pageCount}</p>
    <ul>
      {data.allAirtable.nodes.slice([startIndex], [endIndex]).map(node => (

        <li key={node.id}>
          {node.data.Name} <br />
          {node.data.Area} <br />
          {node.data.Year} <br />
        </li>

      ))}
    </ul>
    <button>More</button>
  </div>
 )}

 export default IndexPage

Search for 'load more in gatsby' ...

'Initial' gatsby query is for generate static content (gatsby 'server' doesn't exists later) - 'load more' is dynamic, can't be done this way , only paginaltion possible - see gatsby docs. Also read about 'fetch build and run time' .

Dynamics can be done with 'normal' (for react - run time) graphql client (fe apollo)... or loading some prepared, generated (by gatsby) static json files with fetch/axios.

There are a few ways to do this. For some use cases it makes sense to run a GraphQL server that you query client side (eg with Apollo) and use GraphQL stitching in Gatsby to render initial content server side. For something simpler, like loading more posts in a feed, you would be well served by pre-compiled responses for each of those expected queries. I've done this in the past by querying for the data I want in gatsby-node.js and writing out JSON files with the chunked data (in public ) and issuing normal HTTP queries for those files as needed from the client-side. This should be relatively straightforward, but if you need more help or an example implementation let me know in the comments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM