Skip to content

Commit

Permalink
use response to latest request
Browse files Browse the repository at this point in the history
  • Loading branch information
Yen Truong committed Nov 18, 2021
1 parent 5385506 commit f6b53ad
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
4 changes: 2 additions & 2 deletions sample-app/src/components/SearchBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,8 @@ export default function SearchBar({
] = useAutocomplete(isVertical);

async function executeQuery () {
await responseToLatestRequestRef.current;
if (autocompleteResponse?.inputIntents.includes(SearchIntent.NearMe)) {
const responseToLatestRequest = await responseToLatestRequestRef.current;
if (responseToLatestRequest?.inputIntents.includes(SearchIntent.NearMe)) {
const position = await SearchHandler.getUserLocation(geolocationOptions);
answersActions.setUserLocation({
latitude: position.coords.latitude,
Expand Down
11 changes: 8 additions & 3 deletions sample-app/src/hooks/useAutocomplete.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ import { AutocompleteResponse, useAnswersActions } from '@yext/answers-headless-

export function useAutocomplete(
isVertical: boolean
): [ AutocompleteResponse|undefined, MutableRefObject<Promise<void>>, () => Promise<void> ] {
): [
AutocompleteResponse|undefined,
MutableRefObject<Promise<AutocompleteResponse|undefined>>,
() => Promise<void>
]
{
const answersActions = useAnswersActions();
const autocompleteNetworkIds = useRef({ latestRequest: 0, responseInState: 0 });
const [ autocompleteResponse, setAutocompleteResponse ] = useState<AutocompleteResponse>();
const responseToLatestRequestRef = useRef<Promise<void>>(Promise.resolve());
const responseToLatestRequestRef = useRef<Promise<AutocompleteResponse|undefined>>(Promise.resolve(undefined));
async function executeAutocomplete () {
const requestId = ++autocompleteNetworkIds.current.latestRequest;
responseToLatestRequestRef.current = new Promise(async (resolve) => {
Expand All @@ -19,7 +24,7 @@ export function useAutocomplete(
autocompleteNetworkIds.current.responseInState = requestId;
}
if (requestId === autocompleteNetworkIds.current.latestRequest) {
resolve();
resolve(response);
}
});
}
Expand Down

0 comments on commit f6b53ad

Please sign in to comment.