Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Fuse from 'fuse.js'
- import React, { useState, useEffect } from 'react'
- import { useStaticQuery, graphql } from 'gatsby'
- export default () => {
- const data = useStaticQuery(graphql`
- {
- allMarkdownRemark {
- nodes {
- frontmatter {
- title
- tags
- date(formatString: "MMMM Do, YYYY")
- }
- fields {
- slug
- timestamp
- views
- }
- id
- excerpt(pruneLength: 1000000)
- }
- }
- }
- `)
- const allResults = data.allMarkdownRemark.nodes
- // allResults looks similar to this:
- //
- // [
- // {
- // frontmatter: { ... }
- // fields: { ... }
- // id
- // excerpt
- // },
- // ....
- // ]
- const [results, setResults] = useState(allResults)
- const [query, setQuery] = useState('')
- const options = {
- shouldSort: true,
- includeScore: true,
- includeMatches: true,
- threshold: 0.33,
- location: 0,
- distance: 100,
- maxPatternLength: 32,
- minMatchCharLength: 2,
- keys: [
- { name: 'frontmatter.title', weight: 1 },
- { name: 'frontmatter.tags', weight: 0.75 },
- { name: 'frontmatter.excerpt', weight: 0.5 },
- ],
- }
- const fuse = new Fuse(allResults, options)
- useEffect(() => {
- setResults(query ? fuse.search(query) : allResults)
- }, [query])
- return (
- <div>
- <input
- type='search'
- value={query}
- onChange={event => setQuery(event.currentTarget.value)}
- />
- {results.length && (
- <ul>
- {results.map(article => {
- const { id, frontmatter } = article.item || article // <= this is important
- const { title, date } = frontmatter
- return (
- <li key={id}>
- <h2>{title}</h2>
- <p>{date}</p>
- </li>
- )
- })}
- </ul>
- )}
- {!results.length && query && <h2>No results</h2>}
- </div>
- )
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement