Skip to content

Commit

Permalink
move effects to useEffect and fix browser back
Browse files Browse the repository at this point in the history
  • Loading branch information
Aprillion committed Sep 5, 2023
1 parent 5966ed1 commit 2d136db
Showing 1 changed file with 24 additions and 10 deletions.
34 changes: 24 additions & 10 deletions app/components/search.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {useState, useEffect, useRef, MutableRefObject, FocusEvent} from 'react'
import {useState, useEffect, useRef, MutableRefObject, FocusEvent, useCallback} from 'react'
import debounce from 'lodash/debounce'
import {AddQuestion} from '~/routes/questions/add'
import {Action, ActionType} from '~/routes/questions/actions'
Expand Down Expand Up @@ -38,23 +38,38 @@ export default function Search({

const {search, arePendingSearches, results} = useSearch(onSiteAnswersRef, limitFromUrl)

const searchFn = (rawValue: string, initialSearch = false) => {
const searchFn = (rawValue: string) => {
const value = rawValue.trim()
if (value === searchInputRef.current) return

searchInputRef.current = value

search(value)
logSearch(value)

if (queryFromUrl && !initialSearch) {
removeQueryFromUrl()
}
}

if (queryFromUrl && !searchInputRef.current) {
searchFn(queryFromUrl, true)
}
// run search if queryFromUrl is provided initially or if it pops from browser history after it was removed,
// update url if searchInput changes,
// and use current version of functions without affecting deps
const searchInput = searchInputRef.current
const searchFnRef = useRef(searchFn)
searchFnRef.current = searchFn
const removeQueryFromUrlRef = useRef(removeQueryFromUrl)
removeQueryFromUrlRef.current = removeQueryFromUrl
const queryFromUrlWasRemoved = useRef(false)
useEffect(() => {
if (queryFromUrl) {
if (!searchInput || queryFromUrlWasRemoved.current) {
searchFnRef.current(queryFromUrl)
queryFromUrlWasRemoved.current = false
const inputEl = document.querySelector('input[name="searchbar"]') as HTMLInputElement
inputEl.value = queryFromUrl
} else if (queryFromUrl !== searchInput) {
removeQueryFromUrlRef.current()
queryFromUrlWasRemoved.current = true
}
}
}, [queryFromUrl, searchInput])

const handleChange = debounce(searchFn, 100)

Expand Down Expand Up @@ -87,7 +102,6 @@ export default function Search({
name="searchbar"
placeholder={placeholder}
autoComplete="off"
defaultValue={queryFromUrl}
onChange={(e) => handleChange(e.currentTarget.value)}
onKeyDown={(e) => e.key === 'Enter' && searchFn(e.currentTarget.value)}
/>
Expand Down

0 comments on commit 2d136db

Please sign in to comment.