Skip to content

Instantly share code, notes, and snippets.

@farmisen
Created May 3, 2020 15:54
Show Gist options
  • Save farmisen/1a919c62664695c14bb98df3e8db87d2 to your computer and use it in GitHub Desktop.
Save farmisen/1a919c62664695c14bb98df3e8db87d2 to your computer and use it in GitHub Desktop.
User provider
module Provider = {
let make = React.Context.provider(UserContext.context);
let makeProps = (~value, ~children, ()) => {
"value": value,
"children": children,
};
};
type state = {user: UserTypes.user};
let reducer = (_, action) => {
switch (action) {
| UserTypes.UserLoggedIn(userDetails) => {
user: Authenticated(userDetails),
}
| UserTypes.UserLoggedOut => {user: Guest}
};
};
let initialState = {user: Guest};
[@react.component]
let make = (~children) => {
let (state, dispatch) = React.useReducer(reducer, initialState);
let listenAuthEvents = () => {
Amplify.Hub.listen("auth", eventData => {
switch (eventData##payload##event) {
| "signIn" =>
let userDetails: UserTypes.userDetails = {
id: eventData##payload##data##attributes##sub,
username: eventData##payload##data##username,
};
dispatch(UserTypes.UserLoggedIn(userDetails));
| "signOut" => dispatch(UserTypes.UserLoggedOut)
| other => Js.log("Unhandled auth event: " ++ other)
}
});
};
let fetchUserData = () => {
Amplify.Auth.currentAuthenticatedUser()
|> Js.Promise.then_(authData => {
let userDetails: UserTypes.userDetails = {
id: authData##attributes##sub,
username: authData##username,
};
dispatch(UserTypes.UserLoggedIn(userDetails));
Js.Promise.resolve();
});
};
React.useEffect0(() => {
listenAuthEvents();
ignore(fetchUserData());
Some(() => {Amplify.Hub.remove("auth")});
});
<Provider value=(state.user, dispatch)> children </Provider>;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment