Home > other >  React.JS: API called with stale value
React.JS: API called with stale value

Time:06-14

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

CodePudding user response:

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;
}
  • Related