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, NewNotification } from '../../../interfaces'; import { ContentType } from '../Bookmarks'; import { getCategories, addCategory, addBookmark, updateCategory, createNotification } from '../../../store/actions'; import Button from '../../UI/Buttons/Button/Button'; interface ComponentProps { modalHandler: () => void; contentType: ContentType; categories: Category[]; category?: Category; addCategory: (formData: NewCategory) => void; addBookmark: (formData: NewBookmark) => void; updateCategory: (id: number, formData: NewCategory) => void; createNotification: (notification: NewNotification) => void; } const BookmarkForm = (props: ComponentProps): JSX.Element => { const [categoryName, setCategoryName] = useState({ name: '' }) const [formData, setFormData] = useState({ name: '', url: '', categoryId: -1 }) useEffect(() => { if (props.category) { setCategoryName({ name: props.category.name }); } else { setCategoryName({ name: '' }); } }, [props.category]) const formSubmitHandler = (e: SyntheticEvent): void => { e.preventDefault(); if (!props.category) { // Add new if (props.contentType === ContentType.category) { props.addCategory(categoryName); setCategoryName({ name: '' }); } else if (props.contentType === ContentType.bookmark) { if (formData.categoryId === -1) { props.createNotification({ title: 'Error', message: 'Please select category' }) return; } props.addBookmark(formData); setFormData({ name: '', url: '', categoryId: formData.categoryId }) } } else { // Update if (props.contentType === ContentType.category) { props.updateCategory(props.category.id, categoryName); setCategoryName({ name: '' }); } props.modalHandler(); } } 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 === ContentType.category ? ( setCategoryName({ name: e.target.value })} /> ) : ( inputChangeHandler(e)} /> inputChangeHandler(e)} /> ) } {!props.category ? : } ) } const mapStateToProps = (state: GlobalState) => { return { categories: state.bookmark.categories } } const dispatchMap = { getCategories, addCategory, addBookmark, updateCategory, createNotification } export default connect(mapStateToProps, dispatchMap)(BookmarkForm);