AutosuggestAccountInput: prevent race condition by cancelling pending requests

profile-avatar-switcher
Alex Gleason 2021-10-14 10:05:57 -05:00
rodzic 92c164dc6b
commit e8005b9cf6
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 7211D1F99744FBB7
2 zmienionych plików z 13 dodań i 3 usunięć

Wyświetl plik

@ -947,10 +947,10 @@ export function unpinAccountFail(error) {
}; };
} }
export function accountSearch(params) { export function accountSearch(params, cancelToken) {
return (dispatch, getState) => { return (dispatch, getState) => {
dispatch({ type: ACCOUNT_SEARCH_REQUEST, params }); dispatch({ type: ACCOUNT_SEARCH_REQUEST, params });
return api(getState).get('/api/v1/accounts/search', { params }).then(({ data: accounts }) => { return api(getState).get('/api/v1/accounts/search', { params, cancelToken }).then(({ data: accounts }) => {
dispatch(importFetchedAccounts(accounts)); dispatch(importFetchedAccounts(accounts));
dispatch({ type: ACCOUNT_SEARCH_SUCCESS, accounts }); dispatch({ type: ACCOUNT_SEARCH_SUCCESS, accounts });
return accounts; return accounts;

Wyświetl plik

@ -1,6 +1,7 @@
import React from 'react'; import React from 'react';
import AutosuggestInput from './autosuggest_input'; import AutosuggestInput from './autosuggest_input';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { CancelToken } from 'axios';
import ImmutablePureComponent from 'react-immutable-pure-component'; import ImmutablePureComponent from 'react-immutable-pure-component';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { injectIntl, defineMessages } from 'react-intl'; import { injectIntl, defineMessages } from 'react-intl';
@ -29,8 +30,17 @@ class AutosuggestAccountInput extends ImmutablePureComponent {
accountIds: ImmutableOrderedSet(), accountIds: ImmutableOrderedSet(),
} }
source = CancelToken.source();
refreshCancelToken = () => {
this.source.cancel();
this.source = CancelToken.source();
return this.source;
}
handleAccountSearch = throttle(q => { handleAccountSearch = throttle(q => {
const { dispatch } = this.props; const { dispatch } = this.props;
const source = this.refreshCancelToken();
const params = { const params = {
q, q,
@ -38,7 +48,7 @@ class AutosuggestAccountInput extends ImmutablePureComponent {
limit: 4, limit: 4,
}; };
dispatch(accountSearch(params)) dispatch(accountSearch(params, source.token))
.then(accounts => { .then(accounts => {
const accountIds = accounts.map(account => account.id); const accountIds = accounts.map(account => account.id);
this.setState({ accountIds: ImmutableOrderedSet(accountIds) }); this.setState({ accountIds: ImmutableOrderedSet(accountIds) });