JamesBrill / react-speech-recognition

💬Speech recognition for your React app
https://webspeechrecognition.com/
MIT License
696 stars 123 forks source link

update state variable! #60

Closed Cosmin-Ciolacu closed 4 years ago

Cosmin-Ciolacu commented 4 years ago

hi! I created a little vocal app like this with following commands:

const [name, setName] = useState('');
  const commands = [
    {
      command: "my name is *"
      callback:  (name) => {
       setName(name);
      },
    },
    {
      command: "tell my name"
      callback: () => {
        console.log(name);
      },

when I say tell my name in console name its undefined.

JamesBrill commented 4 years ago

Hi @Cosmin-Ciolacu When I tested this example locally, it worked as expected with all the configurations I tried. Here's a simple working example:

import React, { useState } from 'react'
import SpeechRecognition, { useSpeechRecognition } from 'react-speech-recognition'

const Dictaphone = () => {
  const [name, setName] = useState('')
  const commands = [
    {
      command: "my name is *",
      callback: (name) => {
       setName(name);
      },
    },
    {
      command: "tell my name",
      callback: () => {
        alert(name);
      }
    }
  ]

  const { listening } = useSpeechRecognition({ commands })

  const listen = () => SpeechRecognition.startListening()

  if (!SpeechRecognition.browserSupportsSpeechRecognition()) {
    return null
  }

  return (
    <div>
      {!listening && <button onClick={listen}>Listen</button>}
      {listening && <p>Listening...</p>}
      {name && <p>Hi {name}!</p>}
    </div>
  )
}

export default Dictaphone

If this still doesn't work for you, please share the full code for your component that is using react-speech-recognition - perhaps I can help you debug.

Cosmin-Ciolacu commented 4 years ago

it works! thank you very muck!