import { useState, SyntheticEvent, Fragment, ChangeEvent, useEffect } from 'react'; import { connect } from 'react-redux'; import ModalForm from '../../UI/Forms/ModalForm/ModalForm'; import InputGroup from '../../UI/Forms/InputGroup/InputGroup'; import { Category, GlobalState, NewBookmark, NewCategory } from '../../../interfaces'; import { FormContentType } from '../Bookmarks'; import { getCategories, addCategory, addBookmark } from '../../../store/actions'; interface ComponentProps { modalHandler: () => void; contentType: FormContentType; categories: Category[]; addCategory: (formData: NewCategory) => void; addBookmark: (formData: NewBookmark) => void; } const BookmarkForm = (props: ComponentProps): JSX.Element => { const [categoryName, setCategoryName] = useState({ name: '' }) const [formData, setFormData] = useState({ name: '', url: '', categoryId: -1 }) const formSubmitHandler = (e: SyntheticEvent): void => { e.preventDefault(); if (props.contentType === FormContentType.category) { props.addCategory(categoryName); setCategoryName({ name: '' }); } else if (props.contentType === FormContentType.bookmark) { if (formData.categoryId === -1) { alert('select category'); return; } props.addBookmark(formData); setFormData({ name: '', url: '', categoryId: formData.categoryId }) } } const inputChangeHandler = (e: ChangeEvent): void => { setFormData({ ...formData, [e.target.name]: e.target.value }) } const selectChangeHandler = (e: ChangeEvent): void => { setFormData({ ...formData, categoryId: parseInt(e.target.value) }) } return ( {props.contentType === FormContentType.category ? ( setCategoryName({ name: e.target.value })} /> ) : ( inputChangeHandler(e)} /> inputChangeHandler(e)} /> ) } ) } const mapStateToProps = (state: GlobalState) => { return { categories: state.bookmark.categories } } export default connect(mapStateToProps, { getCategories, addCategory, addBookmark })(BookmarkForm);