npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

gatsby-plugin-fusejs

v2.0.2

Published

Gatsby plugin for providing client-side search for data available in Gatsby's GraphQL layer using Fuse.js

Downloads

137

Readme

gatsby-plugin-fusejs

A Gatsby plugin that uses Fuse.js to search your content.

Install

Using react-use-fusejs is strongly recommended. You can use Fuse.js without it, but it will be little tricky to use.

npm install --save gatsby-plugin-fusejs react-use-fusejs

How to use

Create fusejs nodes

Edit gatsby-config.js

module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-fusejs`,
      options: {
        query: `
          {
            allMarkdownRemark {
              nodes {
                id
                rawMarkdownBody
                frontmatter {
                  title
                }
              }
            }
          }
        `,
        keys: ['title', 'body'],
        normalizer: ({ data }) =>
          data.allMarkdownRemark.nodes.map((node) => ({
            id: node.id,
            title: node.frontmatter.title,
            body: node.rawMarkdownBody,
          })),
      },
    },
  ],
}

Options

  • query: A GraphQL query that returns the data to be indexed.
  • keys: An array of keys to index. see Fuse.createIndex
  • normalizer: A function that normalizes the data returned by the query.

Implementing search in your site

The search data is stored in the fusejs node. You can applying debouncing or throttling to the search keyword for additional performance benefits.

import { useStaticQuery, graphql } from 'gatsby'
import * as React from 'react'
import { useGatsbyPluginFusejs } from 'react-use-fusejs'

export function Search() {
  const data = useStaticQuery(graphql`
    {
      fusejs {
        index
        data
      }
    }
  `)

  const [query, setQuery] = React.useState('')
  const result = useGatsbyPluginFusejs(query, data.fusejs)

  return (
    <div>
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <ul>
        {result.map(({ item }) => (
          <li key={item.id}>{item.title}</li>
        ))}
      </ul>
    </div>
  )
}

export default Search

Lazy-loading the search data

The fusejs node also have url for the search data. You can use this url to lazy-load the search data.

Below is an example of lazy-loading the search data when the user starts typing.

import { useStaticQuery, graphql } from 'gatsby'
import * as React from 'react'
import { useGatsbyPluginFusejs } from 'react-use-fusejs'

export function Search() {
  const data = useStaticQuery(graphql`
    {
      fusejs {
        publicUrl
      }
    }
  `)

  const [query, setQuery] = React.useState('')
  const [fusejs, setFusejs] = React.useState(null)
  const result = useGatsbyPluginFusejs(query, fusejs)

  const fetching = React.useRef(false)

  React.useEffect(() => {
    if (!fetching.current && !fusejs && query) {
      fetching.current = true

      fetch(data.fusejs.publicUrl)
        .then((res) => res.json())
        .then((json) => setFusejs(json))
    }
  }, [fusejs, query])

  return (
    <div>
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <ul>
        {result.map(({ item }) => (
          <li key={item.id}>{item.title}</li>
        ))}
      </ul>
    </div>
  )
}

export default Search

Reusing the search data

You can prevent re-fetching the search data every time the component is mounted by using context.

// src/context/app.jsx
import { createContext, useState } from 'react'

export const AppContext = createContext({
  fusejs: null,
  setFusejs: () => {},
})

export const AppProvider = ({ children }) => {
  const [fusejs, setFusejs] = useState(null)

  return (
    <AppContext.Provider value={{ fusejs, setFusejs }}>
      {children}
    </AppContext.Provider>
  )
}
// gatsby-browser.js
import { AppProvider } from './src/context/app'

export const wrapRootElement = ({ element }) => {
  return <AppProvider>{element}</AppProvider>
}
// src/components/Search.jsx
import { AppContext } from '../context/app'
import { graphql, useStaticQuery } from 'gatsby'
import * as React from 'react'
import { useGatsbyPluginFusejs } from 'react-use-fusejs'

export function Search() {
  const data = useStaticQuery(graphql`
    {
      fusejs {
        publicUrl
      }
    }
  `)

  const [query, setQuery] = React.useState('')
  const [fusejs, setFusejs] = React.useContext(AppContext)
  const result = useGatsbyPluginFusejs(query, fusejs)

  const fetching = React.useRef(false)

  React.useEffect(() => {
    if (!fetching.current && !fusejs && query) {
      fetching.current = true

      fetch(data.fusejs.publicUrl)
        .then((res) => res.json())
        .then((json) => setFusejs(json))
    }
  }, [fusejs, query])

  return (
    <div>
      <input
        type="text"
        value={query}
        onChange={(e) => setQuery(e.target.value)}
      />
      <ul>
        {result.map(({ item }) => (
          <li key={item.id}>{item.title}</li>
        ))}
      </ul>
    </div>
  )
}

export default Search