Warning Displays When Using Okta Docs to Add User Auth to React App

If you follow these instructions to integrate react-router with Okta’s OpenID Connect API to authenticate users you will get the following error message:

This won’t prevent your app from running but it could cause performance issues. :rocket: The most common reason for this warning is usually because setState() is being called on a component after it’s been unmounted. The code that causes this warning to display is the sample code on this page in the Okta how-to guide. This is the part where we’re actually rendering user info onto the page, after they’ve logged in. :cowboy_hat_face:

Luckily, this is easily resolved! :+1: I followed this guide to fix it.

Based on the above referenced guide, the updated class-based component is as follows:

import { withOktaAuth } from "@okta/okta-react";
import React, { Component } from "react";

async function checkUser() {
  if (this.props.authState.isAuthenticated && !this.state.userInfo) {
    const userInfo = await this.props.authService.getUser();
    if (this._isMounted) {
      this.setState({ userInfo });
    }
  }
}

export default withOktaAuth(
  class Profile extends Component {
    _isMounted = false;

    constructor(props) {
      super(props);
      this.state = { userInfo: null };
      this.checkUser = checkUser.bind(this);
    }

    async componentDidMount() {
      this._isMounted = true;
      this.checkUser();
    }

    async componentDidUpdate() {
      this._isMounted = true;
      this.checkUser();
    }

    componentWillUnmount() {
      this._isMounted = false;
    }

    render() {
      return (
        <div>
          {this.state.userInfo && (
            <div>
              <p>Welcome back, {this.state.userInfo.name}!</p>
            </div>
          )}
        </div>
      );
    }
  }
);