Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

252
Visualizações
React.JS: API called with stale value

I have a function that makes a call to API to fetch the id of a particular resource. This id is then passed to a second API call as a delete request. Problem is that first API is correctly returnign the value but the second called is still executed with a stale value (initially assigned value).

I suppose this is a problem of parallel processing maybe? Can someone please provide any guidance? My code and output is attached. "4" is the correct id returned from the first API but the second call is still made with "-1".

export function deleteBook(title: string): Promise<Book> {
    let bookId = -1;
    findBook(title).then((response) => {
        bookId = Number(response[0].id);
        console.log(bookId);
    });

    let API = apiURL + `/api/books/${bookId}`;
    return axiosInstance
        .delete(API)
        .then((responseJson) => {
            return Promise.resolve(responseJson.data);
        })
        .catch((error) => {
            return Promise.reject(error);
        });
}

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You're currently kicking off findBook, but not waiting for it to finish. Immediately after starting findBook, you do the delete with bookId = -1. Some time later, findBook will finish, but that's too late to help the delete. Any code that needs to wait on findBook, needs to be in the .then callback (either the immediate one, or one farther down the promise chain).

export function deleteBook(title: string): Promise<Book> {
  return findBook(title)
    .then(response => {
      const bookId = Number(response[0].id);
      const API = apiURL + `/api/books/${bookId}`;
      return axiosInstance.delete(API);
    })
    .then(responseJson => {
      return responseJson.data; // No need to wrap it in Promise.resolve, you're already in a .then callback
    });
    // No need to catch and then reject; that's the same as not catching it at all
}

If you prefer async/await, the same code would be:

export async function deleteBook(title: string): Promise<Book> {
  const response = await findBook(title);
  const bookId = Number(response[0].id);
  const API = apiURL + `/api/books/${bookId}`;
  const responseJson = await axiosInstance.delete(API);
  return responseJson.data;
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda