import { Component, Prop, Vue, Watch } from 'vue-property-decorator'
import ResponseErrors from '../../types/ResponseErrors'

@Component
export default class BaseFormField extends Vue {
  @Prop(Object) errors?: ResponseErrors
  @Prop({ type: String }) name?: string

  get hasError(): boolean {
    return (
      !!this.errors &&
      !!this.name &&
      this.name in this.errors &&
      !!this.errors[this.name]
    )
  }

  @Watch('hasError', { immediate: true })
  clearError(hasError: boolean) {
    if (hasError) {
      const unbind = this.$watch('$attrs.value', () => {
        if (this.errors && this.name) {
          this.$delete(this.errors, this.name)
        }

        unbind()
      })
    }
  }
}
