0

Trying to use a setState function and no matter where I use it, it is coming back as undefined?

const StreamingCaptionViewer = () => {
  const [trans, setTrans] = useState(null);
  const [sentidata, setSentidata] = useState();
  const [entidata, setEntidata] = useState();
  const socket = useSocket('transcript', (data) => {
    console.log(`data recieved: ${JSON.stringify(data)}`);
    setTrans(data);
  });

  this.setSentidata = this.setSentidata.bind(this);  // Here is the error (undefined)

  const ErrorMessage = {
    color: 'red',
    fontSize: '13px',
    visibility: 'hidden',
  };
jdog
  • 10,351
  • 29
  • 90
  • 165
  • lambda expressions have a lexical `this`. Do not use `this` inside functional components. Declare the inner properties as variables. Eg: `const innerProp ='foo'` https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4 – Dupocas Aug 26 '21 at 13:08

2 Answers2

2

You're not using a class component so there's no need for this. You can simply setSentidata(whatever)

imjared
  • 19,492
  • 4
  • 49
  • 72
0

If it is a functional component, you have access to the hook directly inside the function.

You dont need to bind the hook, i.e. , you need not write: this.setSentidata = this.setSentidata.bind(this);

Your can directly use setSentidata(what you want to set sentidata to)

madmax
  • 1
  • 2