title: React native fetch token and then get to user details using fetch api
body: <p>I am building login app using React native. For auth, I am using spring boot app. </p>
  
  <p>Here is use case.</p>
  
  <ol>
  <li>User visit to client's login screen and enters username and password.</li>
  <li>React native send request to the server using fetch API.</li>
  <li>If the token object comes back then login (username/password) are correct. </li>
  <li>If the token is correct app should make another call to the server to get user details by token. </li>
  </ol>
  
  <p>Problem is - how I can first API call to validate login and get token and once get the valid token to make another API call to get user details.</p>
  
  <p>Here is the code:</p>
  
  <pre><code>import { dologin,getUser } from "../../API";
  </code></pre>
  
  <p>And Login handeler</p>
  
  <pre><code>handleLogin = () =&gt; {
      const { username, password } = this.state
  
      if (username.length == 0 || password.length == 0){
          this.setState({
            errorMessage: 'Login and password is required.',
            loginProcessing: false,
          });
      } else {
  
        this.setState({errorMessage: null});
  
  
        dologin(username, password).then(accessToken =&gt; {
  
          if(!accessToken.state){
            this.setState({
              errorMessage: accessToken.data,
              loginProcessing: false,
            });
            return null;
          } else{
            return accessToken.data;
          }
        });
  
      }
  }
  </code></pre>
  
  <p>Fetch API</p>
  
  <pre><code>//get user by token
  export const getUser = (token) =&gt; {
  if(token == null) return null;
  return fetch('http://localhost:8080/api/user/get', {
      method: 'GET',
      headers: {"Authorization": "Bearer " + token}
  }).then((response) =&gt; {
    console.log(response.json());
      return response.json();
  }).catch((err) =&gt; {
      console.log(err);
  })
  }
  
  
  export const dologin = (username, password) =&gt; {
  
    var details = {
       username: username,
       password: password,
       grant_type:'password'
   };
  
   var formBody = [];
    for (var property in details) {
        var encodedKey = encodeURIComponent(property);
        var encodedValue = encodeURIComponent(details[property]);
        formBody.push(encodedKey + "=" + encodedValue);
    }
  
  
    return fetch('http://localhost:8080/oauth/token', {
          method: 'POST',
          headers: {
              "Authorization": "Basic " + btoa("enrecover:EsTEsBDETSEWAvAWcsI"),
              "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
          },
          body: formBody.join("&amp;")
      }).then(res =&gt; {
          if(res.status === 200){
              return {status: true, data:res.json() }
          } else {
              return {status: false, data:"Invalid username or password." }
          }
      })
  }
  </code></pre>