Skip to content

Instantly share code, notes, and snippets.

@mono0x
Created March 15, 2020 12:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mono0x/a307324b1b49a8430a382b1144df5d98 to your computer and use it in GitHub Desktop.
Save mono0x/a307324b1b49a8430a382b1144df5d98 to your computer and use it in GitHub Desktop.
import { useMemo } from "react"
import { useStaticQuery } from "gatsby"
export const useSearch = (searching) => {
const { allMarkdownRemark } = useStaticQuery(graphql`
query {
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date] },
) {
edges {
node {
fields { slug }
frontmatter {
title
date
}
rawMarkdownBody
}
}
}
}
`)
const index = useMemo(() => allMarkdownRemark.edges.map(({ node }) => ({
slug: node.fields.slug,
title: node.frontmatter.title,
date: node.frontmatter.date,
body: node.rawMarkdownBody,
})), [allMarkdownRemark.edges])
const results = useMemo(() => {
const words = searching.toLowerCase().split(/\s+/)
return index.filter(item =>
[item.slug, item.title, item.body].some(content => words.some(word => content.toLowerCase().includes(word)))
)
}, [index, searching])
return results
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment