Created
May 3, 2020 15:54
-
-
Save farmisen/1a919c62664695c14bb98df3e8db87d2 to your computer and use it in GitHub Desktop.
User provider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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