Skip to content

Commit

Permalink
forms: RemoteSelectField: Make request cancellable
Browse files Browse the repository at this point in the history
  • Loading branch information
sakshamarora1 authored and kpsherva committed Aug 12, 2024
1 parent 536c84c commit e26b6cf
Showing 1 changed file with 14 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/lib/forms/RemoteSelectField.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import queryString from "query-string";
import React, { Component } from "react";
import { Message } from "semantic-ui-react";
import { SelectField } from "./SelectField";
import { withCancel } from "../api";

const DEFAULT_SUGGESTION_SIZE = 20;

Expand All @@ -39,6 +40,10 @@ export class RemoteSelectField extends Component {
};
}

componentWillUnmount() {
this.cancellableAction && this.cancellableAction.cancel();
}

onSelectValue = (event, { options, value }, callbackFunc) => {
const { multiple } = this.props;
const newSelectedSuggestions = options.filter((item) => value.includes(item.value));
Expand Down Expand Up @@ -76,9 +81,10 @@ export class RemoteSelectField extends Component {
};

onSearchChange = _debounce(async (e, { searchQuery }) => {
this.cancellableAction && this.cancellableAction.cancel();
await this.executeSearch(searchQuery);
// eslint-disable-next-line react/destructuring-assignment
}, this.props.debounceTime);
}, this.props.debounceTime); // can't destructure as prop variable is used outside the inner function

executeSearch = async (searchQuery) => {
const { preSearchChange, serializeSuggestions } = this.props;
Expand Down Expand Up @@ -119,8 +125,8 @@ export class RemoteSelectField extends Component {
searchQueryParamName,
} = this.props;

try {
const response = await axios.get(suggestionAPIUrl, {
this.cancellableAction = withCancel(
axios.get(suggestionAPIUrl, {
params: {
[searchQueryParamName]: searchQuery,
size: DEFAULT_SUGGESTION_SIZE,
Expand All @@ -132,7 +138,11 @@ export class RemoteSelectField extends Component {
// https://github.com/axios/axios/issues/3316
paramsSerializer: (params) =>
queryString.stringify(params, { arrayFormat: "repeat" }),
});
})
);

try {
const response = await this.cancellableAction.promise;
return response?.data?.hits?.hits;
} catch (e) {
console.error(e);
Expand Down

0 comments on commit e26b6cf

Please sign in to comment.