Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.82 KB | None | 0 0
  1. import Fuse from 'fuse.js'
  2. import React, { useState, useEffect } from 'react'
  3. import { useStaticQuery, graphql } from 'gatsby'
  4.  
  5. export default () => {
  6. const data = useStaticQuery(graphql`
  7. {
  8. allMarkdownRemark {
  9. nodes {
  10. frontmatter {
  11. title
  12. tags
  13. date(formatString: "MMMM Do, YYYY")
  14. }
  15. fields {
  16. slug
  17. timestamp
  18. views
  19. }
  20. id
  21. excerpt(pruneLength: 1000000)
  22. }
  23. }
  24. }
  25. `)
  26.  
  27. const allResults = data.allMarkdownRemark.nodes
  28.  
  29. // allResults looks similar to this:
  30. //
  31. // [
  32. // {
  33. // frontmatter: { ... }
  34. // fields: { ... }
  35. // id
  36. // excerpt
  37. // },
  38. // ....
  39. // ]
  40.  
  41. const [results, setResults] = useState(allResults)
  42. const [query, setQuery] = useState('')
  43.  
  44. const options = {
  45. shouldSort: true,
  46. includeScore: true,
  47. includeMatches: true,
  48. threshold: 0.33,
  49. location: 0,
  50. distance: 100,
  51. maxPatternLength: 32,
  52. minMatchCharLength: 2,
  53. keys: [
  54. { name: 'frontmatter.title', weight: 1 },
  55. { name: 'frontmatter.tags', weight: 0.75 },
  56. { name: 'frontmatter.excerpt', weight: 0.5 },
  57. ],
  58. }
  59.  
  60. const fuse = new Fuse(allResults, options)
  61.  
  62. useEffect(() => {
  63. setResults(query ? fuse.search(query) : allResults)
  64. }, [query])
  65.  
  66. return (
  67. <div>
  68. <input
  69. type='search'
  70. value={query}
  71. onChange={event => setQuery(event.currentTarget.value)}
  72. />
  73. {results.length && (
  74. <ul>
  75. {results.map(article => {
  76. const { id, frontmatter } = article.item || article // <= this is important
  77. const { title, date } = frontmatter
  78. return (
  79. <li key={id}>
  80. <h2>{title}</h2>
  81. <p>{date}</p>
  82. </li>
  83. )
  84. })}
  85. </ul>
  86. )}
  87. {!results.length && query && <h2>No results</h2>}
  88. </div>
  89. )
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement