equicolor
6/10/2016 - 5:11 PM

auth.mobx.js

import {observable, computed, action, extendObservable} from 'mobx';
import axios from 'axios';
import _ from 'lodash';

//validations
const isNotEmpty = {
  check: field => field !== undefined && field.trim() !== '',
  message: name => `${name} cannot be empty!`
}

//state
class AuthState {

  @observable loading = true;
  @observable loadingUser;
  @observable errors = [];
  @observable user;
  @observable email;
  @observable password;
  @observable submittedOnce = false;

  formFields = [
    {
      name: 'User',
      value: this.email,
      validations: [isNotEmpty]
    },
    {
      name: 'Password',
      value: this.password,
      validations: [isNotEmpty]
    }
  ].map(fieldDef => extendObservable(fieldDef, {value: fieldDef.value}))

  @action setEmail = email => this.email = email;
  @action setPassword = password => this.password = password;

  @computed get isFormValid() {
    return _.every(this.formFields, field => {
      return _.every(field.validations, validation => validation.check(field.value))
    });
  }

  @action checkAuth = () => {
    setTimeout(() => {
      this.loading = false;
    }, 500);
  }

  @action login = (email, password) => {
    this.submittedOnce = true;

    this.loadingUser = true;
    axios.post('/api/user/login', {
      email: this.email,
      password: this.password
    }).then(result => {
      this.errors = [];
      this.loadingUser = false;
      this.user = result;
    }).catch(error => {
      this.errors.push(error.data);
      this.loadingUser = false;
    });
  }

  @action logout = () => {
    this.user = undefined;
    this.loading = false;
    this.loadingUser = false;
    this.errors = [];
  }

}

export default AuthState;