3

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)
  }
}
5
  • Are you calling setUserName somewhere? Commented Nov 11, 2019 at 13:15
  • 1
    You may want to use console.log(username); directly to be able to see what the object actually is. Commented Nov 11, 2019 at 13:16
  • how are you calling setUserName ? Commented Nov 11, 2019 at 13:17
  • 2
    You code seems incomplete please add the whole snippet Commented Nov 11, 2019 at 13:17
  • you might have other things wrong in your code, I tried your code in stackblitz stackblitz.com/edit/react-hmomr2 and its working well Commented Nov 11, 2019 at 13:18

2 Answers 2

1

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"/>

Sign up to request clarification or add additional context in comments.

Comments

0

Got the solution I made a mistake on this line onChange={()=>setPassword(event.target.value)}

now it is solved by this line

onChangeText={text => setPassword(text)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.