Last active
September 13, 2022 00:58
-
-
Save silesky/e98c55f282655936dc6e7655e16202f8 to your computer and use it in GitHub Desktop.
LoginForm/logic.js with async/await
This file contains 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 from 'react'; | |
import withState from 'recompose/withState'; | |
import withHandlers from 'recompose/withHandlers'; | |
import compose from 'recompose/compose'; | |
import getContext from 'recompose/getContext'; | |
const withConfig = getContext({ config: React.PropTypes.object }); | |
const withEmailState = withState('email', 'setEmail', ''); | |
const withPasswordState = withState('password', 'setPassword', ''); | |
const withFetchState = withState('fetching', 'setFetching', false); | |
const withLoginErrorState = withState('loginError', 'setLoginError', false); | |
const withFormHandlers = withHandlers({ | |
setEmail: props => event => props.setEmail(event.target.value), | |
setPassword: props => event => props.setPassword(event.target.value), | |
continueAsGuest: ({ setContinueAsGuest }) => | |
event => { | |
event.preventDefault(); | |
setContinueAsGuest(); | |
}, | |
doLogin: props => | |
async (email, password) => { | |
const loginToGetUser = async () => { | |
const formData = new global.FormData(); | |
formData.append('email', email); | |
formData.append('password', password); | |
const res = await global.fetch( | |
`${props.config.api_url}/en/widgets/donate/user-login`, | |
{ | |
method: 'POST', | |
credentials: 'include', | |
body: formData, | |
}, | |
); | |
if (res.ok) return res.json(); | |
throw res; | |
}; | |
try { | |
props.setFetching(true); | |
const user = await loginToGetUser(); | |
if (!user.authenticated) throw new Error('login failed'); | |
props.setUserData(user); | |
props.setUser(user); | |
} catch (err) { | |
props.setLoginError(true); | |
} finally { | |
props.setFetching(false); | |
} | |
}, | |
}); | |
export default compose( | |
withConfig, | |
withEmailState, | |
withPasswordState, | |
withFetchState, | |
withLoginErrorState, | |
withFormHandlers, | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment