简体   繁体   中英

Why React JS useEffect hook is not refreshing the text?

I am using Google Speech-To-Text API for answering questions of my web page using user's speech. In this case I have created all of the Node JS server side functions correctly, when I start API then server sends the text of speech constantly to client using webSockets. My issue is on the React JS client.js file. When received the text of speech to client from server , the useEffect is not refresh the #text-field(input tag) of web browser.

client.js file

import io from 'socket.io-client';
import React from 'react';
import ReactDOM from 'react-dom';
import { useEffect, useState } from 'react';

const socket = io('http://localhost:3000', {
  transports: ['websocket', 'polling']
});

const App = ({}) => {
  const [data, setData] = useState([]);

  useEffect(() => {
    socket.on('speech', textOfSpeech => {
      setData(currentData => [...currentData, textOfSpeech ]);
    });
  }, []);

  return (
    <div>
      <h1>Message</h1>
      <input id="text-field" type="text" value={data.join('')}/>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById('root')); ```

When I refresh the web page, then all text of speech display in the #text-field , without refreshing the web page I can not get the text of speech. Please help me to update the #text-field without refreshing the web page .

Since the dependency array for useEffect is empty array it runs only once. You can refer these links

Don't forget that in order for useEffect to pick up any change in your state you have to pass a pointer to it via the dependency array.

const [data, setData] = useState([]);

useEffect(() => {
  socket.on('speech', textOfSpeech => {
    setData(currentData => [...currentData, textOfSpeech ]);
  });
}, [data]);

Have a look at the docs to better understand how useEffect works "under the hood":)

On contrally son, you're code is just right, you dont need dependency on the dependency array since it will cause the hook to run everytime dependency changes and in effect that will cause multiple register of the same handler for the speech and that in return will cause your speech event handler to run multiply with just one event which is not good.

with you're codes, you can just start simple debugging as

socket.on('speech', speech => {
 // console.log('does this receive speech')?
});

that is to say, does socket event runs?... start there. try different browsers, but you're codes is just okey son!

if the console works, then we can start to think about the hook

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM