• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

216
Views
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 3 years ago · Juan Pablo Isaza
1 answers
Answer question

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 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error