import { useState, useEffect } from 'react' import htmlParser from 'html-react-parser' import Loader from '../../components/Loader' import useAPI from '../../hooks/useAPI' import api from '../../utils/api' import '../../public/css/pages/admin.css' const AddEditFunction = (props) => { const [, categories] = useAPI('/categories') const [inputState, setInputState] = useState(props.defaultInputState) const [message, setMessage] = useState('') const [isLoading, setIsLoading] = useState(false) useEffect(() => { if (categories.length > 0 && !props.isEditing) { handleChange({ target: { name: 'categorieId', value: categories[0].id } }) } }, [categories]) const apiCallFunction = (formData) => { if (props.isEditing) return api.put(`/admin/functions/${inputState.id}`, formData, { headers: { Authorization: props.user.token } }) return api.post('/admin/functions', formData, { headers: { Authorization: props.user.token } }) } const handleChange = (event, isTypeCheck = false) => { const inputStateNew = { ...inputState } inputStateNew[event.target.name] = (event.target.files != null) ? event.target.files[0] : (isTypeCheck) ? event.target.checked : event.target.value setInputState(inputStateNew) } const handleSubmit = (event) => { event.preventDefault() setIsLoading(true) const formData = new window.FormData() formData.append('type', inputState.type) formData.append('categorieId', inputState.categorieId) formData.append('title', inputState.title) formData.append('slug', inputState.slug) formData.append('description', inputState.description) formData.append('image', inputState.image) if (props.isEditing) { formData.append('isOnline', inputState.isOnline) } apiCallFunction(formData) .then(() => { setIsLoading(false) window.location.reload(true) }) .catch((error) => { setMessage(`

Erreur: ${error.response.data.message}

`) setIsLoading(false) }) } return ( <>