From cd9ac771291e9aaf2017b7bc094da068aeb4c7e4 Mon Sep 17 00:00:00 2001 From: Daniel O'Connell Date: Wed, 17 Jul 2024 12:15:50 +0200 Subject: [PATCH] better handling of state in search --- app/components/search.tsx | 10 +++++----- app/routes/questions.toc.ts | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/app/components/search.tsx b/app/components/search.tsx index 1e403a6a..135b9c40 100644 --- a/app/components/search.tsx +++ b/app/components/search.tsx @@ -1,4 +1,4 @@ -import {useEffect, useState} from 'react' +import {useEffect, useRef, useState} from 'react' import {useSearchParams} from '@remix-run/react' import debounce from 'lodash/debounce' import {useSearch} from '~/hooks/useSearch' @@ -33,15 +33,15 @@ export default function Search({limitFromUrl, className}: Props) { } } + // This ugly thing here is so that the useEffect doesn't need `searchFn` as its dependancy + const searchFnRef = useRef(searchFn) + searchFnRef.current = searchFn useEffect(() => { const query = searchParams.get('q') if (loadedQuestions && query) { - searchFn(query) + searchFnRef.current(query) setShowResults(true) } - // Properly adding all dependancies would require transforming `searchFn` into a callback - // or something, which in turn would cause this `useEffect` to be called a lot more often. - // eslint-disable-next-line react-hooks/exhaustive-deps }, [loadedQuestions, searchParams]) const handleChange = debounce(searchFn, 100) diff --git a/app/routes/questions.toc.ts b/app/routes/questions.toc.ts index 79c79f56..dd1d3f3a 100644 --- a/app/routes/questions.toc.ts +++ b/app/routes/questions.toc.ts @@ -80,7 +80,7 @@ export const loadToC = async (request: any): Promise => { return { data: data .filter(canBeShown) - .filter(({tags}) => tags.includes(INTRODUCTORY) || tags.includes(ADVANCED)) + .filter(({tags}) => tags?.includes(INTRODUCTORY) || tags?.includes(ADVANCED)) .map(formatQuestion(1)) .sort((a, b) => (a.order || 0) - (b.order || 0)), timestamp,