import React, { useState } from 'react'; import { Button, Modal, Form } from 'react-bootstrap'; import Swal from 'sweetalert2'; export default function EditCourse({ course, fetchData }) { //state for courseId for the fetch URL const [courseId, setCourseId] = useState(''); //Forms state //Add state for the forms of course const [name, setName] = useState(''); const [description, setDescription] = useState('') const [price, setPrice] = useState('') //state for editCourse Modals to open/close const [showEdit, setShowEdit] = useState(false) //function for opening the modal const openEdit = (courseId) => { //to still get the actual data from the form fetch(`${process.env.REACT_APP_API_URL}/courses/${ courseId }`) .then(res => res.json()) .then(data => { //populate all the input values with course info that we fetched setCourseId(data._id); setName(data.name); setDescription(data.description); setPrice(data.price) }) //Then, open the modal setShowEdit(true) } const closeEdit = () => { setShowEdit(false); setName('') setDescription('') setPrice(0) } //function to update the course const editCourse = (e, courseId) => { e.preventDefault(); fetch(`${process.env.REACT_APP_API_URL}/courses/${ courseId }`, { method: 'PUT', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${localStorage.getItem('token')}` }, body: JSON.stringify({ name: name, description: description, price: price }) }) .then(res => res.json()) .then(data => { console.log(data) if(data === true) { Swal.fire({ title: 'Success!', icon: 'success', text: 'Course Successfully Updated' }) closeEdit(); fetchData(); } else { Swal.fire({ title: 'Error!', icon: 'error', text: 'Please try again' }) closeEdit(); fetchData(); } }) } return( <> {/*Edit Modal Forms*/}
editCourse(e, courseId)}> Edit Course Name setName(e.target.value)} required/> Description setDescription(e.target.value)} required/> Price setPrice(e.target.value)} required/>
) }