Then works but await doesn't work with Promise from thunk action

126 Views Asked by At

I'm using redux/toolkit and have a thunk action to request an update API then do navigation.

I try to return a promise so that I can wait for the operation to complete before navigation.

The issue begins when after API calls. If I use then the Promise works s expected with no issue when I navigate afterward.

But when I use it with await dispatch(updatePost()) I start to get a memory leak warnings and suspecting that the Promise might has not been resolved before the navigation. I try to setTimeOut the navigation for 5s then there's no warnings any more. Issue happens whether API call is successful or not.

// Thunk action trying to return a Promise
export function updatePost() {
  return () =>
    services
      .update()
      .then((response: any) => {
         dispatch(updateFn())
         return response?.data
      })
      .catch((error: any) => {
        throw error
      });
}

// This works fine
updatePost().then(() => {
     navigation('/page');
})

// This cause memory leak warnings
await updatePost();
navigation('/page');

The reason I need to use await is that I have more function to use with Promise.all. Please help if you know what's issue. Thanks.

1

There are 1 best solutions below

0
Barry Michael Doyle On

The problem here is that updatePost is not a promise, so even the .then that you call on it isn't "really" valid and going to work like you expect.

You'll need to update updatePost to a promise like this:

export async function updatePost() {
  try {
    const response = await services.update();
    dispatch(updateFn());
    return response?.data;
  } catch (error) {
    throw error;
  }
}

Now you can safely use it like this:

await updatePost();
navigation('/page');