Skip to content

Commit

Permalink
fix(SearchBar): reset state when query/filters change
Browse files Browse the repository at this point in the history
  • Loading branch information
adarshpastakia committed Oct 19, 2024
1 parent 176e3c4 commit 597fe83
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions packages/searchbar/src/searchbar/SearchBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import { Button, useDebounce, useLocalStorage } from "@react-fabric/core";
import { AutoComplete, Field } from "@react-fabric/form";
import { dedupe, EMPTY_ARRAY, isArray } from "@react-fabric/utilities";
import { useMemo, useReducer, useState } from "react";
import { useEffect, useMemo, useReducer, useState } from "react";
import { useTranslation } from "react-i18next";
import { FilterBar } from "../filterbar/FilterBar";
import {
Expand All @@ -40,6 +40,7 @@ interface SearchState {
}

type SearchActions =
| { type: "reset"; query: string | string[]; filters: FilterObject[] }
| { type: "dirty"; dirty: boolean }
| { type: "query"; query: string | string[] }
| { type: "filter"; filters: FilterObject[] };
Expand Down Expand Up @@ -85,6 +86,9 @@ export const SearchBar = ({

const [state, dispatch] = useReducer(
(state: SearchState, action: SearchActions) => {
if (action.type === "reset") {
return { ...state, query: action.query, filters: action.filters };
}
if (action.type === "dirty") {
return { ...state, dirty: action.dirty };
}
Expand All @@ -105,6 +109,10 @@ export const SearchBar = ({
},
);

useEffect(() => {
dispatch({ type: "reset", filters, query });
}, [filters, query]);

const updateHistory = (value: string | string[]) => {
const historyEntry = isArray(value) ? value : [value];
setHistory(dedupe([...historyEntry, ...history]).slice(0, historyCount));
Expand Down Expand Up @@ -139,7 +147,6 @@ export const SearchBar = ({
decorateStart={decorateStart}
onInput={() => dispatch({ type: "dirty", dirty: true })}
onSelect={updateHistory}
onQuery={onQuery}
data-testid="searchbar-input"
onEnterPressed={() => fireSearch(state.query, state.filters)}
/>
Expand Down

0 comments on commit 597fe83

Please sign in to comment.