0

I'm working on a React project where I have a logic flow for checking answers in a language learning app. Each step of the process involves playing some audio. My issue is that the audio from different thunks overlaps because the thunks don't wait for the audio to finish before executing the next one.

Here's the core function I'm using to handle answer checking:

async function handleCheckAnswer(card: string) {
  const incorrectChoices = currentGraphemes.filter(
    (grapheme: string) => grapheme !== wordToBuildArray?.[0],
  );
  const attemptData = {
    studentChoice: card,
    correctChoice: wordToBuildArray?.[0],
    incorrectChoices: incorrectChoices,
    servedWord: wordToBuild,
  };

  if (card === wordToBuildArray?.[0]) {
    await dispatch(handleCorrectAnswerThunk(card, attemptData));

    if (wordToBuildArray.length <= 1) {
      await dispatch(handleWordCompletedThunk(wordToBuild));
    } else {
      await playNextLetterPrompt(wordToBuild);
      dispatch(setIsInteractionAllowed(true));
    }
  } else {
    await dispatch(handleIncorrectAnswerThunk(attemptData, card));
  }
}

And this is an example of one of my thunks:

export function handleCorrectAnswerThunk(card: string, attemptData: any) {
  return async (
    dispatch: ThunkDispatch<RootState, undefined, AnyAction>,
    getState: () => RootState,
  ) => {
    dispatch(setIsInteractionAllowed(false));
    await correctAnswerSfx();
    await playWordWeaverCorrectFeedback(card);
    dispatch(addAttempt(attemptData));
    dispatch(updatePartiallySpelledWord(card));
    dispatch(checkAndCompleteWord());
  };
}

I am using Redux Toolkit for state management. My main problem is that the handleCheckAnswer function does not seem to properly await the handleCorrectAnswerThunk and other thunks, leading to the audio overlap issue.

Questions:

  1. How can I ensure that the audio in one thunk completes before the next thunk starts?
  2. Is there a better approach to handling these asynchronous actions within thunks in Redux Toolkit?

Thank you!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.