github.com/grafviktor/keep-my-secret@v0.9.10-0.20230908165355-19f35cce90e5/website/src/components/Home/Note/index.jsx (about)

     1  import get from 'lodash/get'
     2  import noop from 'lodash/noop'
     3  import isUndefined from 'lodash/isUndefined'
     4  import {useContext, useState} from 'react'
     5  import ApplicationContext from '../../../context'
     6  
     7  import './style.css'
     8  
     9  export default () => {
    10    const {
    11      secret,
    12      navigateTo,
    13      createSecret,
    14      updateSecret,
    15      setAlertMessage,
    16    } = useContext(ApplicationContext)
    17  
    18    const type = 'note'
    19    const secretID = get(secret, 'id')
    20    const [note, setNote] = useState(get(secret, 'note', ''))
    21    const [title, setTitle] = useState(get(secret, 'title', ''))
    22  
    23    const setValue = (event) => {
    24      const field = get(event, 'target.id', '')
    25      const value = get(event, 'target.value', '')
    26  
    27      const changeValueHandler = {
    28        note  : setNote,
    29        title : setTitle,
    30      }[field] || noop
    31  
    32      changeValueHandler(value)
    33    }
    34  
    35    const onSubmitButtonClick = async () => {
    36      const apiHandler = isUndefined(secretID) ? createSecret : updateSecret
    37  
    38      try {
    39        await apiHandler({
    40          id: secretID,
    41          type,
    42          title,
    43          note,
    44        }, secretID)
    45  
    46        navigateTo('home')
    47      } catch (error) {
    48        console.warn(error.message)
    49        setAlertMessage(`Error: ${error.message}`)
    50      }
    51    }
    52  
    53    return (
    54      <div className="kms-secret-edit">
    55        <form className="kms-secret-edit__form">
    56          <div className="row gy-3">
    57            <div className="col-md-12">
    58              <label htmlFor="title" className="form-label">Title</label>
    59              <input type="text" className="form-control" id="title" value={title} onChange={setValue} />
    60            </div>
    61  
    62            <div className="col-md-12">
    63              <label htmlFor="note" className="form-label">Leave your secret note here</label>
    64              <textarea className="form-control" id="note" value={note} rows="15" onChange={setValue} />
    65            </div>
    66          </div>
    67        </form>
    68        <div className="kms-secret-edit__controls">
    69          <button type="button" className="btn btn-primary kms-button-add" onClick={onSubmitButtonClick}>
    70            Save
    71          </button>
    72          <button type="button" className="btn btn-danger kms-button-add" onClick={() => navigateTo('home')}>
    73            Cancel
    74          </button>
    75        </div>
    76      </div>
    77    )
    78  }