Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to handle useState in React?

I’m a beginner in react..
I’m currently practicing by changing the code to FP.

In the process of manipulating the state in React, I put {value:"x"} using useState, but the value does not come out. Do you know where I am going wrong?

class code

class Square extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: null,
    };
  }

  render() {
    return (
      <button
        className="square"
        onClick={() => this.setState({value: "X"})} 
      >
        {this.state.value}
      </button>
    );
  }
}

FC code


function Square (props){
 
    const [message , setMessage] = useState({value:null});

    console.log(message);
    return (
        <button className="square" onClick={()=> setMessage({value:"x"}) } > //Error
            {setMessage.value} //Error
        </button>
    )
}


MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should use message.value instead of setMessage.value

function Square (props){
 
    const [message , setMessage] = useState({value:null});

    console.log(message);
    return (
        <button className="square" onClick={()=> setMessage({value:"x"})} >
            {message.value}
        </button>
    )
}

In this useState, message is state to use, setMessage is for updating states

const [message , setMessage] = useState({value:null});

P/s: You have a syntax problem at onClick. I modified it for you too

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading