Cancelling New Labels

In notebook:
Building Modern Web Apps
Created at:
2016-01-31
Updated:
2016-02-02
Tags:
libraries JavaScript React Ampersand
If not saved and user hits cancel, just destroy the model
  // ****     components/label-item.js        ****
import React form 'react'
import ampersandMixin form 'ampersand-react-mixin'

export default React.createClass({
    mixins: [ampersandMixin]
    
    onDeletClick (event) { ... }
    
    onEditClick () { ... },
    
    onCancelClick () { 
        event.preventDefault()
        // ++++ 1. add canceling logic
        const {label} = this.props
        if(label.saved) {
            // move previous canel logic here
            label.editing = false
            this.setState(this.getInitialState())
        } else {
            // destroy label
            label.destroy()
        }
    },
    
    getInitialState () { ... },
    
    onNameChange (event) { ... },
    
    onColorChange (event) {...},
    
    onSubmit(event) {
        event.preventDefault()
        if (label.saved) {
            this.props.label.update(this.state)
        } else {
            label.save(this.state, 
            // ++++ 2. set the saved state to true 
            // on success
            {
                success: () => label.saved = true
            }
            )
        }
        this.props.label.editing = false
    },
    
    render () {
        const {label} = this.props
        const {color} = this.state
        const cssColor = '#' + color
        let content
        
        if (label.editing) { 
            content = (
                <form onSubmit={this.onSubmit} className='label'>
                    ...
                    <span style={{backgroundColor: cssColor}} className="..." />
                    <input name='name' type='text' value={this.state.name} onChange={this.onNameChange} />
                    
                    <input name='color' onChange={this.onColorChange}  value={cssColor} />
                </form>
            )
        } else {
            content = (
                <div className='label'>
                    ...
                </div>    
            )
        }
        return (<div>{content}</div>)
    }
})  
Funny byproduct: you can only add one new label since the name is the id, and when it's empty, it would be the same and the ampersand collection doesn't let two identical ids.Re audience question, we also need to set saved state when we save a new label (see above change "++++ 2".