Save to local storage

by Allie Yu

HTML

<div class="main">
  <h3>
    Click the button to save to storage
  </h3>
  <div id="root"></div>
</div>

CSS

button {
  margin-left: 10px;
}

JavaScript

//https://codepen.io/dmitri_pavlutin/pen/NaGgVw
//https://dmitripavlutin.com/7-architectural-attributes-of-a-reliable-react-component/

//2 responsibilities: 
//manage form fields  
//saving the input value to store
class PersistentForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { inputValue: localStorage.getItem('inputValue') };
    this.handleChange = this.handleChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  render() {
    const { inputValue } = this.state;
    return (
      <div>
        <input type="text" value={inputValue} 
          onChange={this.handleChange}/> 
        <button onClick={this.handleClick}>Save to storage</button>
      </div>
    )
  }
  
//change component's state gets updated
  handleChange(event) {
    this.setState({
      inputValue: event.target.value
    });
  }

//value is saved to local storage
  handleClick() {
    localStorage.setItem('inputValue', this.state.inputValue);
  }
}

ReactDOM.render(<PersistentForm />, document.getElementById('root')); 


// one responsibility: render form fields and attach event handlers
/* 
The component receives the stored input value from a prop initialValue, and saves the input value using a prop function saveValue(newValue). These props are provided by withPersistence() HOC using props proxy technique. 
*/
class PersistentForm extends Component {  
  constructor(props) {
    super(props);
    this.state = { inputValue: props.initialValue };
    this.handleChange = this.handleChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }

  render() {
    const { inputValue } = this.state;
    return (
      <div className="persistent-form">
        <input type="text" value={inputValue} 
          onChange={this.handleChange}/> 
        <button onClick={this.handleClick}>Save to storage</button>
      </div>
    );
  }

  handleChange(event) {
    this.setState({
      inputValue: event.target.value
    });
 ...