diff --git a/README.md b/README.md index 5785e03..c678b2f 100644 --- a/README.md +++ b/README.md @@ -271,8 +271,22 @@ If the API call has not returned yet, `isLoading: true`. If the API call has not If the API call returned a non-200 or there was an error in making the API call itself, `error` contains the parsed JSON value. +### V. Consuming auth state with `useCheckAuth()` hook -### V. Refresh state (eg: logout) +You can use `useCheckAuth()` hook. It returns the same values as ``\`s render prop parameters. + +For example, +```javascript +import {useCheckAuth} from "react-check-auth"; + +function User(props) { + const {userInfo, isLoading, error, refreshAuth} = useCheckAuth(); + + return {...} +} +``` + +### VI. Refresh state (eg: logout) If you implement a logout action in your app, the auth state needs to be updated. All you need to do is call the `refreshAuth()` function available as an argument in the renderProp function of the `AuthConsumer` component. @@ -294,7 +308,7 @@ For example: This will re-run the call to `authUrl` and update all the child components accordingly. -### VI. Using with React Native +### VII. Using with React Native Usage with React Native is exactly the same as with React. However you would typically use a Authorization header instead of cookies. Here's a quick example: diff --git a/src/lib/context.js b/src/lib/context.js index c107630..de80744 100644 --- a/src/lib/context.js +++ b/src/lib/context.js @@ -7,6 +7,7 @@ const defaultState = { refreshAuth: () => true }; -const { Provider, Consumer } = React.createContext(defaultState); +const AuthContext = React.createContext(defaultState); +const { Provider, Consumer } = AuthContext; -export { Provider, Consumer, defaultState }; +export { AuthContext, Provider, Consumer, defaultState }; diff --git a/src/lib/index.js b/src/lib/index.js index 8238f68..c675945 100644 --- a/src/lib/index.js +++ b/src/lib/index.js @@ -1,4 +1,5 @@ import AuthProvider from './components/AuthProvider'; import AuthConsumer from './components/AuthConsumer'; +import useCheckAuth from './useCheckAuthHook'; -export { AuthProvider, AuthConsumer }; +export { AuthProvider, AuthConsumer, useCheckAuth }; diff --git a/src/lib/useCheckAuthHook.js b/src/lib/useCheckAuthHook.js new file mode 100644 index 0000000..6a9a35d --- /dev/null +++ b/src/lib/useCheckAuthHook.js @@ -0,0 +1,6 @@ +import {useContext} from 'react'; +import {AuthContext} from './context'; + +export default function useCheckAuth () { + return useContext(AuthContext) +}