Created
March 15, 2020 12:37
-
-
Save mono0x/a307324b1b49a8430a382b1144df5d98 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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