-1

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.

pucca garu
  • 97
  • 9
  • Perhaps I'm misunderstanding your explanation, but I don't see any Thunk function or any Redux code here *other than* the `dispatch(updateFn())` in the Promise chain. Can you [edit] to clarify better what you are trying to do and what the issue is? See also [mcve]. – Drew Reese Apr 22 '23 at 08:57

1 Answers1

0

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');
Barry Michael Doyle
  • 9,333
  • 30
  • 83
  • 143