Actualmente estoy creando algunas aplicaciones usando Typescript y React. Hasta la fecha, he usado algunas soluciones malolientes para la siguiente situación de la que me gustaría deshacerme. Tal vez conozcas una mejor manera de hacerlo.
La configuración: Tener un componente React que debe mostrar datos que se obtienen del servidor en la entrada del usuario. Ejemplo de caso de uso: obtener el nombre de una ciudad de una API según un código postal ingresado por usuario. Implementación de ejemplo:
import * as React from 'react';
export interface IXmplState {
plc: string;
name: string;
}
export default class Xmpl extends React.Component<{}, IXmplState> {
constructor(props){
super(props);
this.state = {name: "", plc: ""};
}
private fetchName(plc: string): Promise<string> {
//Fetch data from server.
}
private updateName(plc: string): void {
this.fetchName(plc).then(newName => this.setState({name: newName}));
}
public render(): React.ReactElement<{}> {
return(
<div>
<input value={this.state.plc} onChange={(event) => this.updateName(event.target.value)}/>
<div>{this.state.name}</div>
</div>
);
}
}
El problema:
Tan pronto como cambia la entrada del usuario, se llama a updateName() , que luego actualiza el state en la promesa resuelta. Considere el siguiente caso:
¿Hay formas de suprimir tal comportamiento? ¿Existen formas/bibliotecas específicas para hacer esto en React, TypeScript o Javascript? ¿O generalmente se debe evitar ese tipo de manejo de entrada? ¿Cuál sería una mejor manera o la mejor manera de manejar tal escenario en general?
saludos y gracias
EDITAR: en aras de la exhaustividad.
Mi forma actual de manejar tales escenarios es introducir una suma de verificación en el componente y solo actualizar el estado si la suma de verificación aún no se modifica.
export default class Xmpl extends React.Component<{}, IXmplState> {
let nameCkSm: number = 0;
...
private updateName(plc: string): void {
let ckSm = ++this.nameCkSm;
this.fetchName(plc).then(newName => this.setState(() => {
if(this.nameCkSm === ckSm) return {name: newName};
}));
}
AbortController (característica web estándar, no una biblioteca) es bueno para esto, vea los comentarios *** :
export default class Xmpl extends React.Component<{}, IXmplState> {
// *** An AbortController for the update
pendingNameController: AbortController | null = null;
constructor(props: IXmplState) {
super(props);
this.state = { name: "", plc: "" };
}
// *** Accept the signal
private fetchName(plc: string, signal?: AbortSignal): Promise<string> {
// Fetch data from server, pass `signal` if the mechanism supports
// it (`fetch` and `axios` do, for instance)
}
private updateName(plc: string): void {
// *** Cancel any outstanding call
this.pendingNameController?.abort();
// *** Get a controller for this call, and its signal
this.pendingNameController = new AbortController();
const { signal } = this.pendingNameController;
// *** Pass the signal to the `fetchName` method
this.fetchName(plc, signal)
.then((name) => {
// *** Don't update if the request was cancelled (ideally you'd
// never get here because a cancelled request won't fulfill the
// promise, but race conditions can mean you would)
if (!signal.aborted) {
this.setState({ name });
}
})
.catch((error) => {
// ...handle.report error...
})
}
public render(): React.ReactElement<{}> {
// ...
}
}
Puede escribir una utilidad que maneje múltiples solicitudes pendientes para diferentes cosas envolviendo el método de recuperación, etc. Pero ese es el mecanismo básico para usar AbortController para esto.
Su mayor enemigo aquí es la solicitud de la red y el hecho de que algunos toman más tiempo que otros, lo que resulta en condiciones de carrera en las que las cosas suceden fuera de orden.
Lo más importante que debe hacer es abortar la solicitud anterior y dejar que la "más reciente" tenga prioridad. Esto se hace con la ayuda de un AbortController .
Sé que probablemente no le gustará esto, pero le recomiendo encarecidamente que cambie a componentes y ganchos funcionales. La razón por la que digo esto es porque es mucho más fácil organizar su código para las diferentes cosas que suceden, lo que facilitará la prevención de la condición de carrera. En particular, el gancho useEffect tiene un mecanismo para cancelar el efecto anterior... en este caso su solicitud de API. Así es como se vería (no probado, pero debería ser muy parecido):
// This is a hook whose only purpose is to make an http request any time the searchQuery changes.
// It takes care of cancelling the previous request
const useSearchRequest = (searchQuery) => {
const [state, setState] = useState({ isLoading: false, error: null, result: null });
useEffect(() => {
if (searchQuery) {
// update the state to show we are loading
setState(prevState => ({ ...prevState, isLoading: true }));
try {
// create the abort controller and pass the signal to the request
const controller = new AbortController();
fetch(`/search?query=${searchQuery}`, { signal: controller.signal })
.then(req => req.json())
.then(result => {
// update the state with the results
setState({ isLoading: false, error: null, result });
});
} catch(error) {
// update the state with the error
setState(prevState => ({ ...prevState, isLoading: false, error }));
}
// any time searchQuery changes, this method will be called and will cancel the previous request
return () => controller.abort();
}
// this tells the effect to rerun every time searchQuery changes
}, [searchQuery]);
return state;
}
const Xmpl = () => {
const [searchVal, setSearchVal] = useState('');
const { isLoading, error, result } = useSearchRequest(searchVal);
return(
<div>
{isLoading ? 'loading...' : null}
{error ? `There was an error: ${err}` : null}
<input value={searchVal} onChange={(event) => setSearchVal(event.target.value)}/>
<div>{result}</div>
</div>
);
}