Avoid side effect in state updater for audio chapter advance
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
+10
-10
@@ -898,8 +898,10 @@ const App = () => {
|
|||||||
const audioRef = useRef(null);
|
const audioRef = useRef(null);
|
||||||
const audioBookRef = useRef(audioBook);
|
const audioBookRef = useRef(audioBook);
|
||||||
const audioNarratorRef = useRef(audioNarrator);
|
const audioNarratorRef = useRef(audioNarrator);
|
||||||
|
const audioStateRef = useRef(audioState);
|
||||||
audioBookRef.current = audioBook;
|
audioBookRef.current = audioBook;
|
||||||
audioNarratorRef.current = audioNarrator;
|
audioNarratorRef.current = audioNarrator;
|
||||||
|
audioStateRef.current = audioState;
|
||||||
|
|
||||||
const playAudioChapter = async (abbrev, chapterNum, narrator) => {
|
const playAudioChapter = async (abbrev, chapterNum, narrator) => {
|
||||||
const res = await fetch(`https://bible.helloao.org/api/BSB/${abbrev}/${chapterNum}.json`);
|
const res = await fetch(`https://bible.helloao.org/api/BSB/${abbrev}/${chapterNum}.json`);
|
||||||
@@ -911,16 +913,14 @@ const App = () => {
|
|||||||
if (!audioRef.current) {
|
if (!audioRef.current) {
|
||||||
audioRef.current = new Audio();
|
audioRef.current = new Audio();
|
||||||
audioRef.current.addEventListener('ended', () => {
|
audioRef.current.addEventListener('ended', () => {
|
||||||
setAudioState((prev) => {
|
const nextChapter = audioStateRef.current.chapter + 1;
|
||||||
const nextChapter = prev.chapter + 1;
|
if (nextChapter > audioStateRef.current.total) {
|
||||||
if (nextChapter > prev.total) {
|
setAudioState({ status: 'idle', chapter: 0, total: 0 });
|
||||||
return { status: 'idle', chapter: 0, total: 0 };
|
return;
|
||||||
}
|
}
|
||||||
playAudioChapter(audioBookRef.current, nextChapter, audioNarratorRef.current).catch(() =>
|
playAudioChapter(audioBookRef.current, nextChapter, audioNarratorRef.current).catch(() =>
|
||||||
setAudioState({ status: 'error', chapter: 0, total: 0 }),
|
setAudioState({ status: 'error', chapter: 0, total: 0 }),
|
||||||
);
|
);
|
||||||
return prev;
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
const audioEl = audioRef.current;
|
const audioEl = audioRef.current;
|
||||||
|
|||||||
Reference in New Issue
Block a user