Skip to content

Commit

Permalink
[Handle Results] Reset results when user query is cleared from search…
Browse files Browse the repository at this point in the history
… bar textarea
  • Loading branch information
pH-7 committed May 3, 2024
1 parent 6ae7f72 commit e68a2aa
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions client/components/SearchForm.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useRef, useState, useCallback } from "react";
import { useNavigate } from 'react-router-dom';
import { useNavigate } from "react-router-dom";
import TextareaAutosize from "react-textarea-autosize";
import { getRandomQuerySuggestion } from "../modules/querySuggestions";
import { debounce } from "../utils/debounce";
Expand All @@ -17,30 +17,36 @@ export function SearchForm({
getRandomQuerySuggestion(),
);

const navigate = useNavigate();
const navigate = useNavigate();

const startSearching = useCallback((queryToEncode: string) => {
updateQuery(queryToEncode);
navigate(`/?q=${encodeURIComponent(queryToEncode)}`);
}, [updateQuery, navigate]);
const startSearching = useCallback(
(queryToEncode: string) => {
updateQuery(queryToEncode);
navigate(`/?q=${encodeURIComponent(queryToEncode)}`);
},
[updateQuery, navigate],
);

const debouncedStartSearching = debounce(startSearching, 3000); // 3000ms = 3s

const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
const userQuery = event.target.value.trim();
const userQueryIsBlank = userQuery.length === 0;
const suggestedQueryIsBlank = suggestedQuery.trim().length === 0;

if (userQueryIsBlank && suggestedQueryIsBlank) {
setSuggestedQuery(getRandomQuerySuggestion());
} else if (!userQueryIsBlank && !suggestedQueryIsBlank) {
setSuggestedQuery("");
}

// Start searching immediately when user types
if (!userQueryIsBlank) {
debouncedStartSearching(userQuery);
}
// If the user deleted the input, reset the search results
else {
debouncedStartSearching("");
}
};

useEffect(() => {
Expand Down

0 comments on commit e68a2aa

Please sign in to comment.