3

I am using js-search to search through some blog posts in my gatsby site. I have been following this tutorial here.

const path = require("path")
const axios = require("axios")
exports.createPages = ({ actions }) => {
  const { createPage } = actions
  return new Promise((resolve, reject) => {
    axios
      .get("https://bvaughn.github.io/js-search/books.json")
      .then(result => {
        const { data } = result
        /**
         * creates a dynamic page with the data received
         * injects the data into the context object alongside with some options
         * to configure js-search
         */
        createPage({
          path: "/search",
          component: path.resolve(`./src/templates/ClientSearchTemplate.js`),
          context: {
            bookData: {
              allBooks: data.books,
              options: {
                indexStrategy: "Prefix match",
                searchSanitizer: "Lower Case",
                TitleIndex: true,
                AuthorIndex: true,
                SearchByTerm: true,
              },
            },
          },
        })
        resolve()
      })
      .catch(err => {
        console.log("====================================")
        console.log(`error creating Page:${err}`)
        console.log("====================================")
        reject(new Error(`error on page creation:\n${err}`))
      })
  })
}

Now if I get back a very big dataset from that axios request, there will be many many blog posts shown on the page. Is there a way for me to setup lazy-loading here for these blog posts, while still being able to search through all of them via gatsby? Or at least just lazy load the images that I get back (I will get back a link to an image in the JSON)?

userjmillohara
  • 457
  • 5
  • 25
  • Hi, i'm just seeing this question, have you found any solution? I will need to implement something similar for a project i'm working on, i think the solution is to add pagination to the search results and then lazy load them on the client side. If it is not late, i will try to make it. let me know – Emidio Torre Dec 09 '20 at 20:37

1 Answers1

0

I think the best way to solve your problem is to do it programmatically. You have all books via props inside your ClientSearchTemplate component. Just write logic with state inside, remember the page and number of items on the page, slice some books while moving from page to page.

Pavel Erastov
  • 83
  • 1
  • 5