auth0-react icon indicating copy to clipboard operation
auth0-react copied to clipboard

withAuthenticationRequired causing infinite loops when calling wrapped component's effect

Open type opened this issue 5 years ago • 5 comments

Describe the problem

Since upgrading to 1.2.0 from 1.0.0, it seems that creating a ProtectedRoute using withAuthenticationRequired leads to infinite remounting of components.

I am using React 16.13.1, react-router-dom 5.2.

This problem does not happen with auth0-react 1.0.0

export const ProtectedRoute = ({
                                component,
                                ...args
                              }: {
  component: ComponentType;
  exact?: boolean;
  path: string;
}) => {
  const Comp = withAuthenticationRequired(component, {});
  // @ts-ignore
  return <Route {...args} render={(props) => <Comp {...props} />} />;
};

Usage that will cause it to break

// imagine this is inside a switch in react-router
<ProtectedRoute component={MyComponent} path="/whatever" />

// now this is our MyComponent, it calls an async thunk

function MyComponent() {
  const fetchResults = async () => {
    try {
      dispatch(someAsyncThunk());
    } catch (err) {
    }
  };

  useEffect(() => {
    fetchResults();
  }, []);

  return (<div>I will just keep calling my effect!</div>)
}

type avatar Dec 23 '20 15:12 type

Hi @type

Can you change your ProtectedRoute component to:

export const ProtectedRoute = ({
                                component,
                                ...args
                              }: {
  component: ComponentType;
  exact?: boolean;
  path: string;
}) => {
  return <Route {...args} render={(props) => {
    // wrap the component inside the render function,
    // to stop withAuthenticationRequired getting recreated
    // on every render
    const Comp = withAuthenticationRequired(component, {});
    return <Comp {...props} />;
  }} />;
};

Let me know if that resolves your problem

adamjmcgrath avatar Dec 23 '20 15:12 adamjmcgrath

Hi @adamjmcgrath , unfortunately this does not fix it. Tested your provided code against 1.2.0 (failed) and 1.0.0 (succeeded), so same result as with the code I provided.

type avatar Dec 23 '20 23:12 type

My bad, I had an axios interceptor that got left in on accident in the App.jsx component that was using getAccessTokenSilently(). This was working okay with 1.0.0 but broke with 1.2.0. But not really a bug!

type avatar Dec 23 '20 23:12 type

Hello,

We had the same issue, and I think it's problematic that we can't use getAccessTokenSilently() in App.jsx while also using redux in protected components.

In case it's useful to anyone, here is how we implemented without withAuthenticationRequired to avoid infinite loops :

const ProtectedRoute = ({
  component: Component,
}: {
  component: React.ComponentType;
}) => {
  const AuthMetadata = useSelector((state: State) => state.auth.entity);
  const { isAuthenticated, isLoading, loginWithRedirect } = useAuth0();

  useEffect(() => {
    // * Useful later to know company in the generic callback page
    // * see getCompanyFromUrlORLocalStorageRedirectUrl();
    if (!isAuthenticated) {
      localStorage.setItem(
        LOCALSTORAGE_ENUM.REDIRECT_URL,
        window.location.href,
      );
    }
  }, [isAuthenticated]);

  const {
    returnTo = `${window.location.pathname}${window.location.search}`,
    onRedirecting = (): JSX.Element => <></>,
    loginOptions = {},
  } = {
    loginOptions: buildLoginOptions(AuthMetadata),
  } as WithAuthenticationRequiredOptions;

  useEffect(() => {
    if (isLoading || isAuthenticated) {
      return;
    }
    const opts = {
      ...loginOptions,
      appState: {
        ...loginOptions.appState,
        returnTo: typeof returnTo === 'function' ? returnTo() : returnTo,
      },
    };
    (async (): Promise<void> => {
      await loginWithRedirect(opts);
    })();
  }, [isLoading, isAuthenticated, loginWithRedirect, loginOptions, returnTo]);

  return isAuthenticated ? <Component /> : onRedirecting();
};```

avinesse avatar Mar 25 '21 09:03 avinesse

It would be awesome to have a hook helper like useLoginRedirectEffect() to do somethings like this


const ProtectedRoute = ({
  component: Component,
}: {
  component: React.ComponentType;
}) => {
  const AuthMetadata = useSelector((state: State) => state.auth.entity);
  const { isAuthenticated, isLoading, loginWithRedirect } = useAuth0();
  const options = {
    loginOptions: buildLoginOptions(AuthMetadata),
  };
  const beforeRedirect = () => {
    if (!isAuthenticated) {
      localStorage.setItem(
        LOCALSTORAGE_ENUM.REDIRECT_URL,
        window.location.href,
      );
    }}
  const [ onRedirecting ] = useLoginRedirectEffect(options, beforeRedirect)
  return isAuthenticated ? <Component /> : onRedirecting();
};

dilhansarica avatar Mar 25 '21 10:03 dilhansarica