Advertisement
Guest User

Untitled

a guest
Jun 10th, 2016
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. import {observable, computed, action, extendObservable} from 'mobx';
  2. import axios from 'axios';
  3. import _ from 'lodash';
  4.  
  5. //validations
  6. const isNotEmpty = {
  7. check: field => field !== undefined && field.trim() !== '',
  8. message: name => `${name} cannot be empty!`
  9. }
  10.  
  11. //state
  12. class AuthState {
  13.  
  14. @observable loading = true;
  15. @observable loadingUser;
  16. @observable errors = [];
  17. @observable user;
  18. @observable email;
  19. @observable password;
  20. @observable submittedOnce = false;
  21.  
  22. formFields = [
  23. {
  24. name: 'User',
  25. value: this.email,
  26. validations: [isNotEmpty]
  27. },
  28. {
  29. name: 'Password',
  30. value: this.password,
  31. validations: [isNotEmpty]
  32. }
  33. ].map(fieldDef => extendObservable(fieldDef, {value: fieldDef.value}))
  34.  
  35. @action setEmail = email => this.email = email;
  36. @action setPassword = password => this.password = password;
  37.  
  38. @computed get isFormValid() {
  39. return _.every(this.formFields, field => {
  40. return _.every(field.validations, validation => validation.check(field.value))
  41. });
  42. }
  43.  
  44. @action checkAuth = () => {
  45. setTimeout(() => {
  46. this.loading = false;
  47. }, 500);
  48. }
  49.  
  50. @action login = (email, password) => {
  51. this.submittedOnce = true;
  52.  
  53. this.loadingUser = true;
  54. axios.post('/api/user/login', {
  55. email: this.email,
  56. password: this.password
  57. }).then(result => {
  58. this.errors = [];
  59. this.loadingUser = false;
  60. this.user = result;
  61. }).catch(error => {
  62. this.errors.push(error.data);
  63. this.loadingUser = false;
  64. });
  65. }
  66.  
  67. @action logout = () => {
  68. this.user = undefined;
  69. this.loading = false;
  70. this.loadingUser = false;
  71. this.errors = [];
  72. }
  73.  
  74. }
  75.  
  76. export default AuthState;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement