Reputation: 11
I'm using Next.js and I'm trying to access SpeechSynthesis browser's API:
window.speechSynthesis.getVoices()
Since I'm using Next.js, I put the call to window
into a useEffect
, and it works fine on first load.
//...
const [voices, setVoices] = useState<SpeechSynthesisVoice[]>([]);
useEffect(() => {
setVoices(window.speechSynthesis.getVoices());
}, []);
//...
But the weirdest of things happen when I reload the page after. I get a misleading error in the console and suddenly window.speechSynthesis.getVoices()
returns nothing.
Do you know why? What should i do differently?
I put my code into a Next.js temnplate in CodeSandBox here for you to take a look.
Thanks in advance for yuour help 🙏
I tried putting the function in useCallback, useMemo... but nothing worked.
Upvotes: 1
Views: 311
Reputation: 1084
Simple answer is Run the function again
. Don't use the recursion. It will give you error.
const [isLoaded, setLoaded] = React.useState(false);
// To load Voices
React.useEffect(() => {
setTimeout(() => setLoaded(true), 300);
}, []);
React.useEffect(() => {
// Don't use this condition here
// if (!isLoaded) return;
const getVoices = () => {
const availableVoices = window.speechSynthesis.getVoices();
if (voices.length) {
setState((prev) => ({ ...prev, availableVoices }));
}
};
getVoices();
}, [isLoaded]);
Upvotes: 0