In this lesson, we go over the
AuthProvider component that will provide the
onegraph-auth object everywhere in our React application.
This component will contain 2
React.useEffects. One will watch
[props.auth, props.appId] and create an auth object if
props.auth does not exist.
useEffect will set the
status in our local state. These are the headers our React application will use to authenticate requests to OneGraph.
Finally, we have our
logout buttons that call
auth.logout respectively. These are the functions we call to log our users in through OneGraph OAuth.
We pass all our local state and our
logout functions to the
AuthContext.Provider that we've created.
Instructor: [0:00] I will make dir src/context. I will touch src/context/AuthContext. Now I'm going to paste in the auth code. This imports OneGraphAuth. Then we create our AuthContext that we will later export from this file. Our AuthProvider is a function that takes the auth object as props. You can see from line 13 to 21 that if props.auth does not exist, then our AuthProvider will create a client for us.
[0:48] The next useEffect will set the headers and the status. This is checking whether the user is logged in when this component mounts. If auth changes, we need to rerun these checks just to keep them synced.
[1:08] Here's our login function. It's a function that basically wraps calls to auth.login. The service parameter will be a string for whatever service that we're calling. In our case, it's GitHub. Then, a callback function to let the caller know that logging in has a CURD, so we pass what is logged in to the callback.
[1:38] Next, we set the service status and the auth headers. These auth headers are what our app will use to authenticate our request.
[1:51] Then, finally, we have our logout function, which has a similar API as our login function. It takes a service, and it just calls auth.logout. This clears our local storage. It's the same sort of function. It sets the status, and isLoggedIn will be false.
[2:16] Then, all of the data that we want to pass to our context.