dankthreads
dankthreads

Reputation: 323

Calling API with refreshed JWT token

Currently using the AWS Cognito SDK for my react application. Currently, when calling an API I run a session check with ComponentWillMount

componentWillMount() {
  if (!this.props.authenticated) {
    this.props.history.push('/auth/login');
  } else {
    getUserFromLocalStorage()
      .then(data => {
        console.log('getUserFromLocalStorage');
        this.props.setUserToReduxState(data);

        console.log(
          'user sucess retrieved from local storage and usersettoreduxstate: ',
          data
        )
        .then(console.log('after local test'))
      })

      .catch(() => {
        logoutUserFromReduxState();
      });
  }
}

and in componentDidMount I call the API with the JWT token from local storage

componentDidMount() {
// calls API with localStage.jwtToken
this.loadData();
}

This works most of the time however when the token expires the JWT gets refreshed which is all taken care of however when the API is called initially it gets called with the old JWT. I can see the new JWT being refreshed in redux but it gets refreshed before the API get's called.

Is there any recommendations to make sure before every API call is made the token is refreshed and updated in redux before used in the API call?

Upvotes: 1

Views: 303

Answers (1)

forJ
forJ

Reputation: 4627

it's likely to be due to asynchronous nature of javascript. Just make sure that this.lodaData() awaits for refresh of token.

For example, componentWillMount runs authentication part and componentDidMount does not wait for the authentication function to finish running before making its API calls.

Now this cannot be done by separating the authentication part and API on top of my head right now but you can put them all in the same event either all in componentWillMount or componentDidMount and make sure that API call gets called AFTER all the authentication. Something like below

refreshToken() {
    return new Promise((resolve, reject) => {
        //refresh token
        resolve()
    })
}

componentDidMount(){
    this.refreshToken().then(() => {
        //API call
    })
}

Upvotes: 1

Related Questions