Created
March 23, 2020 18:25
-
-
Save indatawetrust/c18d72a00073941df606d6dc79dbcdac to your computer and use it in GitHub Desktop.
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
import React, {useContext, useState} from "react"; | |
export default null; | |
const FeathersContext = React.createContext(null); | |
export const useFeathers = () => useContext(FeathersContext); | |
export const FeathersProvider = ({ children, client: feathersClient }) => { | |
const [isLoggedIn, setIsLoggedIn] = useState(false); | |
const [userInfo, setUserInfo] = useState(null); | |
/* | |
* @param data | |
* @param data.user | |
* @param data.accessToken | |
* @return {Object} | |
*/ | |
const successfulLogin = (data) => { | |
const { user } = data; | |
setIsLoggedIn(true); | |
setUserInfo(user); | |
return data; | |
}; | |
/* | |
* @return {Promise} | |
*/ | |
const checkAuth = () => ( | |
feathersClient | |
.get('authentication') | |
.then(successfulLogin) | |
); | |
/* | |
* @param loginInfo | |
* @param loginInfo.email user email | |
* @param loginInfo.password user password | |
* @return {Promise} | |
*/ | |
const login = ({ email = '', password = '' }) => ( | |
feathersClient | |
.authenticate({ | |
strategy: 'local', | |
email, | |
password, | |
}) | |
.then(successfulLogin) | |
); | |
/* | |
* @param registerInfo | |
* @param registerInfo.email user email | |
* @param registerInfo.password user password | |
* @return {Promise} | |
*/ | |
const register = ({ email = '', password = '' }) => ( | |
feathersClient | |
.service('users') | |
.create({ | |
email, | |
password | |
}) | |
); | |
/* | |
* @return {Promise} | |
*/ | |
const reAuth = () => ( | |
feathersClient | |
.reAuthenticate() | |
.then(() => checkAuth()) | |
); | |
/* | |
* @return {Promise} | |
*/ | |
const logout = () => ( | |
feathersClient | |
.logout() | |
.then(() => setIsLoggedIn(false)) | |
); | |
return ( | |
<FeathersContext.Consumer> | |
{() => ( | |
<FeathersContext.Provider | |
value={{ | |
checkAuth, | |
login, | |
register, | |
reAuth, | |
logout, | |
isLoggedIn, | |
userInfo, | |
}} | |
> | |
{children} | |
</FeathersContext.Provider> | |
)} | |
</FeathersContext.Consumer> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment