diff --git a/real_estate/client/src/pages/CreatListing.jsx b/real_estate/client/src/pages/CreatListing.jsx index 405b79c..57a7a50 100644 --- a/real_estate/client/src/pages/CreatListing.jsx +++ b/real_estate/client/src/pages/CreatListing.jsx @@ -1,14 +1,32 @@ import { useState } from "react" import {getDownloadURL, getStorage, ref, uploadBytesResumable} from 'firebase/storage' import {app} from '../firebase' +import {useSelector} from 'react-redux' +import {useNavigate} from 'react-router-dom' + const CreatListing = () => { + const {currentUser} = useSelector((state) => state.user) + const navigate =useNavigate(); const [files, setFiles] = useState([]); const [formData, setFormData] = useState({ imageUrls: [], + name: '', + description: '', + address: '', + type: 'rent', + bed: 1, + bath: 1, + currentPrice: 100, + discountPrice: 0, + offer: false, + parking: false, + furnished: false, }); const [imageUploadError, setImageUploadError] = useState(false); const [upload, setUpload] = useState(false); + const [error, setError] = useState(false); + const [loading, setLoading] = useState(false); const handleImageSubmit = (e) => { if(files.length > 0 && files.length + formData.imageUrls.length < 11){ setUpload(true); @@ -58,83 +76,121 @@ const CreatListing = () => { setFormData({...formData, imageUrls: formData.imageUrls.filter((_, i) => i !== index), }); }; + const handleChange = (e) => { + if (e.target.id === 'sale' || e.target.id === 'rent') { + setFormData({...formData, type: e.target.id, }); + } + if(e.target.id === 'parking' || e.target.id === 'furnished' || e.target.id === 'offer'){ + setFormData({...formData, [e.target.id]: e.target.checked, }); + } + if(e.target.type === 'number' || e.target.type === 'text' || e.target.type === 'textarea'){ + setFormData({...formData, [e.target.id]: e.target.value, }); + } + }; + const handleSubmit = async (e) => { + e.preventDefault(); + try { + if(formData.imageUrls.length < 1) + return setError('You need to upload at least one image'); + if (+formData.currentPrice < +formData.discountPrice) + return setError('Discount must be lower than your current price'); - - - - + setLoading(true); + setError(false); + const res = await fetch('/server/listing/create', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({...formData, userRef: currentUser._id,}), + }); + const data = await res.json(); + setLoading(false); + if(data.success === false){ + setError(data.message) + } + navigate(`/listing/${data._id}`) + } catch (error) { + setError(error.message); + setLoading(false); + + } + } return (