Search code examples
javascriptreactjstypeerrorsetstate

React - TypeError: Cannot read property 'setState' of undefined (Arrow functions)


I am not able to use setState. My code looks something like:

const FormComp = () => {
  const [reader, setReader] = React.useState(0);
//rest of the code
};

const Ques1 = () => {
  return (
    <>
    <button onClick={() => {
                this.setState({ reader: "1" });
              }}>Click</button>
    </>
  )
};

This is just a short version of the code. I'm facing problem in this. Please someone help me out. This code is in same file. UPDATE: tried setReader but it throws an error saying setReader is not defined


Solution

  • Should use like this:

    import React from 'react';
    
    function App() {
      const [reader, setReader] = React.useState(0);
      const FormComp = () => {
      //rest of the code
        return <div>Clicked {reader} times</div>
      };
      
      const Ques1 = () => {
        return (
          <button onClick={() => setReader(reader+1)}>Increase</button>
        )
      };
      return (
        <div className="App">
          <FormComp />
          <Ques1 />
        </div>
      );
    }
    
    export default App;
    

    You can set whatever value you want in setReader function.