React render run before fetch method receives token from server












0















I have a JS file within my React application, which connects to the server, sends username and password, receives an oauth token from the server and stores the token in the local storage.
However before the token received by react, the react sends the next request before token stored in the local storage. Which leads to 401 unauthorized access.



AuthService.js



 login(username, password) {
console.log(username);
return this.fetch(`${this.domain}/api/AuthAPI/getCredentials`, {
headers: {
'Access-Control-Allow-Origin': "*"
}
}).then(res => {
this.fetch(`${this.domain}/Token`, {
method: 'POST',
body: 'grant_type=password&username=' + res[0]
}).then(response => {
var date_token_issue = new Date();
this.setToken(response.access_token,response.expires_in, date_token_issue) // Setting the token in localStorage
return Promise.resolve(response);
})
})

}

setToken(idToken,expires, date_token_issue ) {
localStorage.setItem('id_token', idToken)
localStorage.setItem('expires', expires)
localStorage.setItem('date_token_issue', date_token_issue)
}


SignIn.jsx



import React, { Component } from 'react'
import AuthService from '../comonents/AuthService';
import Orders from '../../app/orders/orders'
import { Redirect, Switch, Route} from "react-router-dom";
export default function SignIn(AuthComponent){
const Auth = new AuthService('http://localhost:53050');

return class AuthWrapped extends Component {
constructor() {
super();
this.state = {
user: null,
loggedIn: false
}
}

async componentDidMount() {
if (!Auth.loggedIn()) {
const promise = await Auth.login('m.dawaina', 'm.dawaina');
console.log(promise)
this.setState({loggedIn: true});
}
else {
try {
this.setState({loggedIn: true})
const profile = Auth.getProfile()
this.setState({
user: profile
})
}
catch(err){
Auth.logout()
//this.props.history.replace('/login')
}
}
}

render() {
if (this.state.loggedIn) {

return (
<div>
<Redirect to='/orders'/>
<Switch>
<Route path="/orders" component={Orders} />
</Switch>
</div>
)
}
else {
return (
<AuthComponent history={this.props.history} user={this.state.user} />
)
}
}

}
}


I need a way to force react wait for the JS receives the token and stores it in the local storage, and prevent react sending the next request until it finds the token stored in the local storage.










share|improve this question



























    0















    I have a JS file within my React application, which connects to the server, sends username and password, receives an oauth token from the server and stores the token in the local storage.
    However before the token received by react, the react sends the next request before token stored in the local storage. Which leads to 401 unauthorized access.



    AuthService.js



     login(username, password) {
    console.log(username);
    return this.fetch(`${this.domain}/api/AuthAPI/getCredentials`, {
    headers: {
    'Access-Control-Allow-Origin': "*"
    }
    }).then(res => {
    this.fetch(`${this.domain}/Token`, {
    method: 'POST',
    body: 'grant_type=password&username=' + res[0]
    }).then(response => {
    var date_token_issue = new Date();
    this.setToken(response.access_token,response.expires_in, date_token_issue) // Setting the token in localStorage
    return Promise.resolve(response);
    })
    })

    }

    setToken(idToken,expires, date_token_issue ) {
    localStorage.setItem('id_token', idToken)
    localStorage.setItem('expires', expires)
    localStorage.setItem('date_token_issue', date_token_issue)
    }


    SignIn.jsx



    import React, { Component } from 'react'
    import AuthService from '../comonents/AuthService';
    import Orders from '../../app/orders/orders'
    import { Redirect, Switch, Route} from "react-router-dom";
    export default function SignIn(AuthComponent){
    const Auth = new AuthService('http://localhost:53050');

    return class AuthWrapped extends Component {
    constructor() {
    super();
    this.state = {
    user: null,
    loggedIn: false
    }
    }

    async componentDidMount() {
    if (!Auth.loggedIn()) {
    const promise = await Auth.login('m.dawaina', 'm.dawaina');
    console.log(promise)
    this.setState({loggedIn: true});
    }
    else {
    try {
    this.setState({loggedIn: true})
    const profile = Auth.getProfile()
    this.setState({
    user: profile
    })
    }
    catch(err){
    Auth.logout()
    //this.props.history.replace('/login')
    }
    }
    }

    render() {
    if (this.state.loggedIn) {

    return (
    <div>
    <Redirect to='/orders'/>
    <Switch>
    <Route path="/orders" component={Orders} />
    </Switch>
    </div>
    )
    }
    else {
    return (
    <AuthComponent history={this.props.history} user={this.state.user} />
    )
    }
    }

    }
    }


    I need a way to force react wait for the JS receives the token and stores it in the local storage, and prevent react sending the next request until it finds the token stored in the local storage.










    share|improve this question

























      0












      0








      0








      I have a JS file within my React application, which connects to the server, sends username and password, receives an oauth token from the server and stores the token in the local storage.
      However before the token received by react, the react sends the next request before token stored in the local storage. Which leads to 401 unauthorized access.



      AuthService.js



       login(username, password) {
      console.log(username);
      return this.fetch(`${this.domain}/api/AuthAPI/getCredentials`, {
      headers: {
      'Access-Control-Allow-Origin': "*"
      }
      }).then(res => {
      this.fetch(`${this.domain}/Token`, {
      method: 'POST',
      body: 'grant_type=password&username=' + res[0]
      }).then(response => {
      var date_token_issue = new Date();
      this.setToken(response.access_token,response.expires_in, date_token_issue) // Setting the token in localStorage
      return Promise.resolve(response);
      })
      })

      }

      setToken(idToken,expires, date_token_issue ) {
      localStorage.setItem('id_token', idToken)
      localStorage.setItem('expires', expires)
      localStorage.setItem('date_token_issue', date_token_issue)
      }


      SignIn.jsx



      import React, { Component } from 'react'
      import AuthService from '../comonents/AuthService';
      import Orders from '../../app/orders/orders'
      import { Redirect, Switch, Route} from "react-router-dom";
      export default function SignIn(AuthComponent){
      const Auth = new AuthService('http://localhost:53050');

      return class AuthWrapped extends Component {
      constructor() {
      super();
      this.state = {
      user: null,
      loggedIn: false
      }
      }

      async componentDidMount() {
      if (!Auth.loggedIn()) {
      const promise = await Auth.login('m.dawaina', 'm.dawaina');
      console.log(promise)
      this.setState({loggedIn: true});
      }
      else {
      try {
      this.setState({loggedIn: true})
      const profile = Auth.getProfile()
      this.setState({
      user: profile
      })
      }
      catch(err){
      Auth.logout()
      //this.props.history.replace('/login')
      }
      }
      }

      render() {
      if (this.state.loggedIn) {

      return (
      <div>
      <Redirect to='/orders'/>
      <Switch>
      <Route path="/orders" component={Orders} />
      </Switch>
      </div>
      )
      }
      else {
      return (
      <AuthComponent history={this.props.history} user={this.state.user} />
      )
      }
      }

      }
      }


      I need a way to force react wait for the JS receives the token and stores it in the local storage, and prevent react sending the next request until it finds the token stored in the local storage.










      share|improve this question














      I have a JS file within my React application, which connects to the server, sends username and password, receives an oauth token from the server and stores the token in the local storage.
      However before the token received by react, the react sends the next request before token stored in the local storage. Which leads to 401 unauthorized access.



      AuthService.js



       login(username, password) {
      console.log(username);
      return this.fetch(`${this.domain}/api/AuthAPI/getCredentials`, {
      headers: {
      'Access-Control-Allow-Origin': "*"
      }
      }).then(res => {
      this.fetch(`${this.domain}/Token`, {
      method: 'POST',
      body: 'grant_type=password&username=' + res[0]
      }).then(response => {
      var date_token_issue = new Date();
      this.setToken(response.access_token,response.expires_in, date_token_issue) // Setting the token in localStorage
      return Promise.resolve(response);
      })
      })

      }

      setToken(idToken,expires, date_token_issue ) {
      localStorage.setItem('id_token', idToken)
      localStorage.setItem('expires', expires)
      localStorage.setItem('date_token_issue', date_token_issue)
      }


      SignIn.jsx



      import React, { Component } from 'react'
      import AuthService from '../comonents/AuthService';
      import Orders from '../../app/orders/orders'
      import { Redirect, Switch, Route} from "react-router-dom";
      export default function SignIn(AuthComponent){
      const Auth = new AuthService('http://localhost:53050');

      return class AuthWrapped extends Component {
      constructor() {
      super();
      this.state = {
      user: null,
      loggedIn: false
      }
      }

      async componentDidMount() {
      if (!Auth.loggedIn()) {
      const promise = await Auth.login('m.dawaina', 'm.dawaina');
      console.log(promise)
      this.setState({loggedIn: true});
      }
      else {
      try {
      this.setState({loggedIn: true})
      const profile = Auth.getProfile()
      this.setState({
      user: profile
      })
      }
      catch(err){
      Auth.logout()
      //this.props.history.replace('/login')
      }
      }
      }

      render() {
      if (this.state.loggedIn) {

      return (
      <div>
      <Redirect to='/orders'/>
      <Switch>
      <Route path="/orders" component={Orders} />
      </Switch>
      </div>
      )
      }
      else {
      return (
      <AuthComponent history={this.props.history} user={this.state.user} />
      )
      }
      }

      }
      }


      I need a way to force react wait for the JS receives the token and stores it in the local storage, and prevent react sending the next request until it finds the token stored in the local storage.







      reactjs asynchronous oauth token fetch






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 25 '18 at 18:45









      Mohamed DawainaMohamed Dawaina

      102




      102
























          1 Answer
          1






          active

          oldest

          votes


















          0














          login(username, password) {
          console.log(username);
          return this.fetch(`${this.domain}/api/AuthAPI/getCredentials`, {
          headers: {
          'Access-Control-Allow-Origin': "*"
          }
          }).then(res => {
          // Add a return here
          return this.fetch(`${this.domain}/Token`, {
          method: 'POST',
          body: 'grant_type=password&username=' + res[0]
          }).then(response => {
          var date_token_issue = new Date();
          this.setToken(response.access_token,response.expires_in, date_token_issue) // Setting the token in localStorage
          return Promise.resolve(response);
          })
          })


          You need to add a return to the then function so that await will wait for the inner promise to resolve.






          share|improve this answer
























          • Thanks Sibin for your valuable answer. The console.log(promise) now returns the token. However the request still sent without token. although when I refresh the page the request sent with token

            – Mohamed Dawaina
            Nov 25 '18 at 19:11











          • ConfigureStore runs before token stored in the localstorage, how can I prevent this

            – Mohamed Dawaina
            Nov 25 '18 at 19:37











          • Are you using redux? How are you calling the ConfigureStore?

            – Sibin
            Nov 25 '18 at 19:49











          • yes i am using redux.

            – Mohamed Dawaina
            Nov 25 '18 at 19:54











          • const client = axios.create({ responseType: 'json' }); client.defaults.headers.common['Authorization'] = 'Bearer ' + Auth.getToken(); console.log('ttt '+ Auth.getToken()); export const configureStore = preloadedState => { const store = createStore( reducers, //custom reducers preloadedState, composeWithDevTools(applyMiddleware(thunk, axiosMiddleware(axios.create(axiosMiddleware(client))), //second parameter options can optionally contain onSuccess, onError, onComplete, successSuffix, errorSuffix )) ) return store; };

            – Mohamed Dawaina
            Nov 25 '18 at 19:54











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53470731%2freact-render-run-before-fetch-method-receives-token-from-server%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          0














          login(username, password) {
          console.log(username);
          return this.fetch(`${this.domain}/api/AuthAPI/getCredentials`, {
          headers: {
          'Access-Control-Allow-Origin': "*"
          }
          }).then(res => {
          // Add a return here
          return this.fetch(`${this.domain}/Token`, {
          method: 'POST',
          body: 'grant_type=password&username=' + res[0]
          }).then(response => {
          var date_token_issue = new Date();
          this.setToken(response.access_token,response.expires_in, date_token_issue) // Setting the token in localStorage
          return Promise.resolve(response);
          })
          })


          You need to add a return to the then function so that await will wait for the inner promise to resolve.






          share|improve this answer
























          • Thanks Sibin for your valuable answer. The console.log(promise) now returns the token. However the request still sent without token. although when I refresh the page the request sent with token

            – Mohamed Dawaina
            Nov 25 '18 at 19:11











          • ConfigureStore runs before token stored in the localstorage, how can I prevent this

            – Mohamed Dawaina
            Nov 25 '18 at 19:37











          • Are you using redux? How are you calling the ConfigureStore?

            – Sibin
            Nov 25 '18 at 19:49











          • yes i am using redux.

            – Mohamed Dawaina
            Nov 25 '18 at 19:54











          • const client = axios.create({ responseType: 'json' }); client.defaults.headers.common['Authorization'] = 'Bearer ' + Auth.getToken(); console.log('ttt '+ Auth.getToken()); export const configureStore = preloadedState => { const store = createStore( reducers, //custom reducers preloadedState, composeWithDevTools(applyMiddleware(thunk, axiosMiddleware(axios.create(axiosMiddleware(client))), //second parameter options can optionally contain onSuccess, onError, onComplete, successSuffix, errorSuffix )) ) return store; };

            – Mohamed Dawaina
            Nov 25 '18 at 19:54
















          0














          login(username, password) {
          console.log(username);
          return this.fetch(`${this.domain}/api/AuthAPI/getCredentials`, {
          headers: {
          'Access-Control-Allow-Origin': "*"
          }
          }).then(res => {
          // Add a return here
          return this.fetch(`${this.domain}/Token`, {
          method: 'POST',
          body: 'grant_type=password&username=' + res[0]
          }).then(response => {
          var date_token_issue = new Date();
          this.setToken(response.access_token,response.expires_in, date_token_issue) // Setting the token in localStorage
          return Promise.resolve(response);
          })
          })


          You need to add a return to the then function so that await will wait for the inner promise to resolve.






          share|improve this answer
























          • Thanks Sibin for your valuable answer. The console.log(promise) now returns the token. However the request still sent without token. although when I refresh the page the request sent with token

            – Mohamed Dawaina
            Nov 25 '18 at 19:11











          • ConfigureStore runs before token stored in the localstorage, how can I prevent this

            – Mohamed Dawaina
            Nov 25 '18 at 19:37











          • Are you using redux? How are you calling the ConfigureStore?

            – Sibin
            Nov 25 '18 at 19:49











          • yes i am using redux.

            – Mohamed Dawaina
            Nov 25 '18 at 19:54











          • const client = axios.create({ responseType: 'json' }); client.defaults.headers.common['Authorization'] = 'Bearer ' + Auth.getToken(); console.log('ttt '+ Auth.getToken()); export const configureStore = preloadedState => { const store = createStore( reducers, //custom reducers preloadedState, composeWithDevTools(applyMiddleware(thunk, axiosMiddleware(axios.create(axiosMiddleware(client))), //second parameter options can optionally contain onSuccess, onError, onComplete, successSuffix, errorSuffix )) ) return store; };

            – Mohamed Dawaina
            Nov 25 '18 at 19:54














          0












          0








          0







          login(username, password) {
          console.log(username);
          return this.fetch(`${this.domain}/api/AuthAPI/getCredentials`, {
          headers: {
          'Access-Control-Allow-Origin': "*"
          }
          }).then(res => {
          // Add a return here
          return this.fetch(`${this.domain}/Token`, {
          method: 'POST',
          body: 'grant_type=password&username=' + res[0]
          }).then(response => {
          var date_token_issue = new Date();
          this.setToken(response.access_token,response.expires_in, date_token_issue) // Setting the token in localStorage
          return Promise.resolve(response);
          })
          })


          You need to add a return to the then function so that await will wait for the inner promise to resolve.






          share|improve this answer













          login(username, password) {
          console.log(username);
          return this.fetch(`${this.domain}/api/AuthAPI/getCredentials`, {
          headers: {
          'Access-Control-Allow-Origin': "*"
          }
          }).then(res => {
          // Add a return here
          return this.fetch(`${this.domain}/Token`, {
          method: 'POST',
          body: 'grant_type=password&username=' + res[0]
          }).then(response => {
          var date_token_issue = new Date();
          this.setToken(response.access_token,response.expires_in, date_token_issue) // Setting the token in localStorage
          return Promise.resolve(response);
          })
          })


          You need to add a return to the then function so that await will wait for the inner promise to resolve.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 25 '18 at 18:59









          SibinSibin

          13614




          13614













          • Thanks Sibin for your valuable answer. The console.log(promise) now returns the token. However the request still sent without token. although when I refresh the page the request sent with token

            – Mohamed Dawaina
            Nov 25 '18 at 19:11











          • ConfigureStore runs before token stored in the localstorage, how can I prevent this

            – Mohamed Dawaina
            Nov 25 '18 at 19:37











          • Are you using redux? How are you calling the ConfigureStore?

            – Sibin
            Nov 25 '18 at 19:49











          • yes i am using redux.

            – Mohamed Dawaina
            Nov 25 '18 at 19:54











          • const client = axios.create({ responseType: 'json' }); client.defaults.headers.common['Authorization'] = 'Bearer ' + Auth.getToken(); console.log('ttt '+ Auth.getToken()); export const configureStore = preloadedState => { const store = createStore( reducers, //custom reducers preloadedState, composeWithDevTools(applyMiddleware(thunk, axiosMiddleware(axios.create(axiosMiddleware(client))), //second parameter options can optionally contain onSuccess, onError, onComplete, successSuffix, errorSuffix )) ) return store; };

            – Mohamed Dawaina
            Nov 25 '18 at 19:54



















          • Thanks Sibin for your valuable answer. The console.log(promise) now returns the token. However the request still sent without token. although when I refresh the page the request sent with token

            – Mohamed Dawaina
            Nov 25 '18 at 19:11











          • ConfigureStore runs before token stored in the localstorage, how can I prevent this

            – Mohamed Dawaina
            Nov 25 '18 at 19:37











          • Are you using redux? How are you calling the ConfigureStore?

            – Sibin
            Nov 25 '18 at 19:49











          • yes i am using redux.

            – Mohamed Dawaina
            Nov 25 '18 at 19:54











          • const client = axios.create({ responseType: 'json' }); client.defaults.headers.common['Authorization'] = 'Bearer ' + Auth.getToken(); console.log('ttt '+ Auth.getToken()); export const configureStore = preloadedState => { const store = createStore( reducers, //custom reducers preloadedState, composeWithDevTools(applyMiddleware(thunk, axiosMiddleware(axios.create(axiosMiddleware(client))), //second parameter options can optionally contain onSuccess, onError, onComplete, successSuffix, errorSuffix )) ) return store; };

            – Mohamed Dawaina
            Nov 25 '18 at 19:54

















          Thanks Sibin for your valuable answer. The console.log(promise) now returns the token. However the request still sent without token. although when I refresh the page the request sent with token

          – Mohamed Dawaina
          Nov 25 '18 at 19:11





          Thanks Sibin for your valuable answer. The console.log(promise) now returns the token. However the request still sent without token. although when I refresh the page the request sent with token

          – Mohamed Dawaina
          Nov 25 '18 at 19:11













          ConfigureStore runs before token stored in the localstorage, how can I prevent this

          – Mohamed Dawaina
          Nov 25 '18 at 19:37





          ConfigureStore runs before token stored in the localstorage, how can I prevent this

          – Mohamed Dawaina
          Nov 25 '18 at 19:37













          Are you using redux? How are you calling the ConfigureStore?

          – Sibin
          Nov 25 '18 at 19:49





          Are you using redux? How are you calling the ConfigureStore?

          – Sibin
          Nov 25 '18 at 19:49













          yes i am using redux.

          – Mohamed Dawaina
          Nov 25 '18 at 19:54





          yes i am using redux.

          – Mohamed Dawaina
          Nov 25 '18 at 19:54













          const client = axios.create({ responseType: 'json' }); client.defaults.headers.common['Authorization'] = 'Bearer ' + Auth.getToken(); console.log('ttt '+ Auth.getToken()); export const configureStore = preloadedState => { const store = createStore( reducers, //custom reducers preloadedState, composeWithDevTools(applyMiddleware(thunk, axiosMiddleware(axios.create(axiosMiddleware(client))), //second parameter options can optionally contain onSuccess, onError, onComplete, successSuffix, errorSuffix )) ) return store; };

          – Mohamed Dawaina
          Nov 25 '18 at 19:54





          const client = axios.create({ responseType: 'json' }); client.defaults.headers.common['Authorization'] = 'Bearer ' + Auth.getToken(); console.log('ttt '+ Auth.getToken()); export const configureStore = preloadedState => { const store = createStore( reducers, //custom reducers preloadedState, composeWithDevTools(applyMiddleware(thunk, axiosMiddleware(axios.create(axiosMiddleware(client))), //second parameter options can optionally contain onSuccess, onError, onComplete, successSuffix, errorSuffix )) ) return store; };

          – Mohamed Dawaina
          Nov 25 '18 at 19:54




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53470731%2freact-render-run-before-fetch-method-receives-token-from-server%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Wiesbaden

          Marschland

          Dieringhausen