From 00aaba2429b3735134fc715120fb5bce6606d3b3 Mon Sep 17 00:00:00 2001 From: lushevol Date: Thu, 30 Mar 2023 17:02:19 +0800 Subject: [PATCH] fix: fix SSR no window error. --- app/components/voice.tsx | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/app/components/voice.tsx b/app/components/voice.tsx index 6752f70f4..fab02d413 100644 --- a/app/components/voice.tsx +++ b/app/components/voice.tsx @@ -1,25 +1,31 @@ // implement a voice component by speech synthesis to read the text with the voice of the user's choice import * as React from "react"; -import { useState } from "react"; +import { useEffect, useState } from "react"; import { IconButton } from "./button"; import VoiceIcon from "../icons/voice.svg"; -const voices = window.speechSynthesis.getVoices(); const speak = ({ text, voice, }: { text: string; - voice?: SpeechSynthesisVoice; + voice: SpeechSynthesisVoice; }) => { - if (!text) return; + if (!window || !text) return; const utterance = new SpeechSynthesisUtterance(text); - utterance.voice = voice || voices[0]; + utterance.voice = voice; window.speechSynthesis.speak(utterance); }; export function Voice(props: { text: string }) { + const [voices, setVoices] = useState([]); const [voice, setVoice] = useState(null); + useEffect(() => { + const voices = window.speechSynthesis.getVoices(); + setVoices(voices); + setVoice(voices[0]); + }, []); + return props.text ? (