import { actionIsLoading } from '../../loading/action'; import { actionLogInSuccess, actionLogInReject, actionLogOutSuccess, actionLogOutReject, } from '../action'; import { setToken, loginUser,updateCredentials,updateUserAvatar } from '../../../api-data'; const asyncCreateUser = (name:string, lastName: string,file:any) => async (dispatch:any) => { try { dispatch(actionIsLoading(true)); const reader: any = new FileReader() const formData:any = new FormData() reader.onload = async () => { formData.append("avatar", file); const data = await Promise.all([updateUserAvatar(formData), updateCredentials(name, lastName)]) const res = data.find(el => el.token) res?.token&&dispatch(actionLogInSuccess(res.token)) } await reader.readAsArrayBuffer(file) } catch (e) { console.log(e) } finally { dispatch(actionIsLoading(false)); } }; const asyncLogin = (number:string, code: string,cb:() => void ) => async (dispatch:any) => { try { dispatch(actionIsLoading(true)); const data = await loginUser<{ token: string, registered: boolean }>(number, code); const token = data?.token const registered = data?.registered if (!token) return setToken.set(token) if (!registered) return cb() dispatch(actionLogInSuccess(token)) } catch (e) { dispatch(actionLogInReject()); cb() } finally { dispatch(actionIsLoading(false)); } }; const asyncLogout = () => async (dispatch:any) => { try { dispatch(actionIsLoading(true)); dispatch(actionLogOutSuccess()); setToken.unset() } catch (e) { dispatch(actionLogOutReject()); } finally { dispatch(actionIsLoading(false)); } }; export { asyncCreateUser, asyncLogin, asyncLogout };