react-keycloak / react-keycloak

React/React Native/NextJS/Razzle components for Keycloak
MIT License
559 stars 133 forks source link

Export the context for use elsewhere or take the consumer himself #85

Closed douglaszaltron closed 4 years ago

douglaszaltron commented 4 years ago

Export the context for use elsewhere or take the consumer himself

{ KeycloakProvider, KeycloakConsumer } from '@react-keycloak/web'

or

{ KeycloakProvider, KeycloakContext } from '@react-keycloak/web'

panz3r commented 4 years ago

Hi @douglaszaltron ,

Thanks for your feedback, can I ask why you need direct access to the KeycloakContext? Can't you use the useKeycloak hook or withKeycloak HOC?

douglaszaltron commented 4 years ago

Hi! Thanks @panz3r To have a different way to access the context in the own component where the provider is inserted, but maybe this is not one of the best approaches, something to be discussed as well. look at the usage example:

<KeycloakProvider>
    <KeycloakContext.Consumer>
      {({ keycloak }) => keycloak && (
             <AxiosProvider token={keycloak.token}>
                  {children}
             </AxiosProvider>
          )}
   </KeycloakContext.Consumer>
</KeycloakProvider>
panz3r commented 4 years ago

Hi @douglaszaltron ,

I see what you need but I would recommend against doing it that way.

I'd suggest you to use the useKeycloak hook (or the withKeycloak HOC) and implement a wrapper around the AxiosProvider component (or if it's a custom one update it) as follow:

import { useKeycloak } from '@react-keycloak/web'

const AuthenticatedAxiosProvider: React.FC<{}> = ({ children }) => {
  const [keycloak, initialized] = useKeycloak()

  return (
    <AxiosProvider token={initialized ? keycloak?.token : undefined}>
      {children}
    </AxiosProvider>
  )
}