Passed
Push — task/application-profile-react... ( f06e77...f3a6a9 )
by Yonathan
05:47
created

UpdatingTextArea.render   A

Complexity

Conditions 3

Size

Total Lines 37
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 23
dl 0
loc 37
rs 9.328
c 0
b 0
f 0
1
import React, { Component } from "react";
2
import _ from "lodash";
3
// Lodash's debounce doesn't work properly if imported
4
// by itself... something to do with how it handles 'this'
5
import TextArea, { TextAreaProps } from "./TextArea";
6
7
export interface UpdatingTextAreaProps extends TextAreaProps {
8
  updateDelay?: number | null;
9
  handleSave: () => void;
10
}
11
12
export interface UpdatingTextAreaState {
13
  updateDelay: number | null | undefined;
14
}
15
16
class UpdatingTextArea extends Component<
17
  UpdatingTextAreaProps,
18
  UpdatingTextAreaState
19
> {
20
  public constructor(props) {
21
    super(props);
22
23
    const { updateDelay } = this.props;
24
25
    if (updateDelay) {
26
      const bounceDelay: number = updateDelay;
27
      this.state = {
28
        updateDelay: bounceDelay,
29
      };
30
      // Lodash's debounce doesn't work properly if imported
31
      // by itself... something to do with how it handles 'this'
32
      this.triggerSave = _.debounce(this.triggerSave, bounceDelay);
33
    }
34
  }
35
36
  public triggerSave(): void {
37
    const { value, minLength, handleSave } = this.props;
38
    if (value !== undefined) {
39
      if (
40
        value.toString().length > (minLength || 3) ||
41
        value.toString().length === 0
42
      ) {
43
        handleSave();
44
      }
45
    }
46
  }
47
48
  public render(): React.ReactElement {
49
    const {
50
      id,
51
      name,
52
      label,
53
      required,
54
      placeholder,
55
      value,
56
      onChange,
57
      errorText,
58
      handleSave,
59
      minLength,
60
      maxLength,
61
    } = this.props;
62
    return (
63
      <TextArea
64
        id={id}
65
        name={name}
66
        label={label}
67
        required={required}
68
        placeholder={placeholder}
69
        value={value}
70
        minLength={minLength}
71
        maxLength={maxLength}
72
        onChange={(event: React.ChangeEvent<HTMLTextAreaElement>): void => {
73
          onChange(event);
74
          if (this.state) {
75
            const { updateDelay } = this.state;
76
77
            if (updateDelay) {
78
              this.triggerSave();
79
            }
80
          }
81
        }}
82
        onBlur={handleSave}
83
        errorText={errorText}
84
      />
85
    );
86
  }
87
}
88
89
export default UpdatingTextArea;
90