Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get values from react hook state

I am new to react native and hooks. In my project I have declared two state properties and I want to get them inside a function. But I am not getting the value from the hook properties.In console it is writing [object object]

const Login =()=> {
  const [username, setUserName] = React.useState('');
  const [password, setPassword] = React.useState('');

  callAPI = async ()=>{
    console.log('api called :' + username)
  }
}
like image 923
Utpal Avatar asked Mar 17 '26 10:03

Utpal


1 Answers

This is a working example of what it looks that you're trying to accomplish.

function mockAPI(username,password) {
  return new Promise((resolve,reject) => {
    setTimeout(()=>resolve(`The API received username: ${username} and pwd: ${password}`),1000);
  });
}

function App() {
  
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  
  function callMockAPI(user,pwd) {
    mockAPI(user,pwd)
    .then((result)=>console.log(result));
  }
  
  return(
    <React.Fragment>
      <div>
        Username: <input type='text' value={username} onChange={()=>setUsername(event.target.value)}/>
      </div>
      <div>
        Password: <input type='password' value={password} onChange={()=>setPassword(event.target.value)}/>
      </div>
      <div>
        <button onClick={()=>callMockAPI(username,password)}>Submit</button>
      </div>
    </React.Fragment>
  );

}

ReactDOM.render(<App/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id="root"/>
like image 160
cbdeveloper Avatar answered Mar 20 '26 07:03

cbdeveloper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!