Skip to the content ForoHackers
Log inJoin

Hi / hola: frontend dev, mucho dolor con el state

FrontendIntroductionsJavaScript and TypeScript
#1133 · spanglish_stacktrace · · Report

Hi, hola. Soy frontend developer, mostly JavaScript y TypeScript, y llevo unos años peleando con una sola pregunta: ¿dónde vive el estado?

My current bug of the week: un useEffect que se dispara dos veces y un fetch que llega fuera de orden. El usuario escribe "ab", la petición de "a" tarda más que la de "ab", y la pantalla muestra los resultados de "a". Classic race condition, pero en el navegador.

La solución que me gusta es ignorar las respuestas viejas:

let latest = 0;

async function search(q) {
  const id = ++latest;
  const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`);
  const data = await res.json();
  if (id !== latest) return;   // llegó tarde, ya hay una petición más nueva
  render(data);
}

Even better is cancelling the old request with AbortController, so it doesn't even finish. Pero el contador es la versión de tres líneas que siempre funciona.

Voy a seguir posteando mis stack traces, en ambos idiomas, porque el error siempre está en inglés y el dolor en español.

#1860 · race_condition_rita · · Report

It is a race condition in a browser, so the same rule applies: define the ordering you want ("last request issued wins") and enforce it explicitly. Your counter does that. One thing to check: if the old request fails after the new one succeeded, make sure the error handler also checks the id, or an old error will clobber the good result.

#1861 · spanglish_stacktrace · · Report

Oof, true, el catch no tenía el check. Fixed. Gracias, Rita: eso me habría salido en producción un viernes.

#1862 · JamonYBash · · Report

Esto es lo mismo que hago en un script cuando lanzo trabajos en paralelo y solo me importa el último resultado: un identificador y descartar los antiguos. Los problemas son los mismos en todos los lenguajes; solo cambian las llaves.

#1863 · polyglot_parser · · Report

The counter trick is a tiny version of a "generation number", which is a recurring idea: a token that says which version of the world a message belongs to. It shows up in caches, databases, and game entities. Grammatically, it is the tense of a message.

Log in or join to reply.