0% found this document useful (0 votes)
5 views

AdForm.tsx

The document outlines a React component for an advertisement posting form that includes fields for title, description, price, category, locations, image upload, and target audience. It incorporates user authentication, reCAPTCHA verification, and automatic sharing of the ad on multiple social media platforms upon successful submission. The form validates user input and provides feedback through toast notifications for errors or successful postings.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

AdForm.tsx

The document outlines a React component for an advertisement posting form that includes fields for title, description, price, category, locations, image upload, and target audience. It incorporates user authentication, reCAPTCHA verification, and automatic sharing of the ad on multiple social media platforms upon successful submission. The form validates user input and provides feedback through toast notifications for errors or successful postings.
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

"use client"

import { useState, useEffect } from "react"


import { useRouter } from "next/navigation"
import { useAdContext } from "@/app/contexts/AdContext"
import { useAuth } from "@/app/contexts/AuthContext"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Label } from "@/components/ui/label"
import { Checkbox } from "@/components/ui/checkbox"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from
"@/components/ui/select"
import { toast } from "@/components/ui/use-toast"
import ReCAPTCHA from "react-google-recaptcha"

const categories = ["Vehicles", "Property", "Jobs", "Services", "For Sale",


"Community"]
const countries = [
"United States",
"Canada",
"United Kingdom",
"Australia",
"Germany",
"France",
"Japan",
"Brazil",
"India",
"South Africa",
"Mexico",
"Spain",
"Italy",
"China",
"Russia",
"Nigeria",
"Egypt",
"Saudi Arabia",
"United Arab Emirates",
"Singapore",
]

export default function AdForm() {


const { addAd, shareAdOnSocialMedia, promoteAd } = useAdContext()
const { user } = useAuth()
const router = useRouter()
const [title, setTitle] = useState("")
const [description, setDescription] = useState("")
const [price, setPrice] = useState("")
const [category, setCategory] = useState("")
const [locations, setLocations] = useState<string[]>([])
const [image, setImage] = useState<File | null>(null)
const [recaptchaValue, setRecaptchaValue] = useState<string | null>(null)

const handleSubmit = async (e: React.FormEvent) => {


e.preventDefault()
if (!user) {
toast({
title: "Authentication required",
description: "Please log in to post an ad.",
variant: "destructive",
})
router.push("/login")
return
}
if (!image) {
toast({
title: "Image required",
description: "Please upload an image for your ad.",
variant: "destructive",
})
return
}

if (locations.length === 0) {
toast({
title: "Location selection error",
description: "Please select at least one country for your ad.",
variant: "destructive",
})
return
}

if (!recaptchaValue) {
toast({
title: "reCAPTCHA verification required",
description: "Please complete the reCAPTCHA verification.",
variant: "destructive",
})
return
}

// Post the ad
postAd()
}

const postAd = async () => {


try {
// In a real-world scenario, you would upload the image to a server or cloud
storage
const imageUrl = URL.createObjectURL(image)

const newAd = {
title,
description,
price: Number.parseFloat(price),
category,
locations,
imageUrl,
userId: user!.id,
targetAudience,
}

const addedAd = addAd(newAd)

// Automatically share on all social media platforms


const platforms: (keyof Ad["socialShares"])[] = [
"facebook",
"twitter",
"instagram",
"tiktok",
"pinterest",
"linkedin",
]
await Promise.all(platforms.map((platform) =>
shareAdOnSocialMedia(addedAd.id, platform)))

toast({
title: "Ad posted successfully",
description: "Your ad has been posted and shared on all social media
platforms.",
})

router.push("/dashboard")
} catch (error) {
console.error("Error posting ad:", error)
toast({
title: "Error",
description: "Failed to post your ad. Please try again.",
variant: "destructive",
})
}
}

return (
<form onSubmit={handleSubmit} className="space-y-4 max-w-xl mx-auto">
<div>
<Label htmlFor="title">Ad Title (Be descriptive for better
visibility)</Label>
<Input id="title" value={title} onChange={(e) => setTitle(e.target.value)}
required />
</div>
<div>
<Label htmlFor="description">Description (Include relevant details to help
your ad appear in searches)</Label>
<Textarea id="description" value={description} onChange={(e) =>
setDescription(e.target.value)} required />
</div>
<div>
<Label htmlFor="price">Price</Label>
<Input id="price" type="number" value={price} onChange={(e) =>
setPrice(e.target.value)} required />
</div>
<div>
<Label htmlFor="category">Category</Label>
<Select onValueChange={setCategory} required>
<SelectTrigger>
<SelectValue placeholder="Select a category" />
</SelectTrigger>
<SelectContent>
{categories.map((cat) => (
<SelectItem key={cat} value={cat}>
{cat}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Label htmlFor="locations">Countries (select all that apply)</Label>
<Select
onValueChange={(value) => {
if (locations.includes(value)) {
setLocations(locations.filter((loc) => loc !== value))
} else {
setLocations([...locations, value])
}
}}
>
<SelectTrigger>
<SelectValue placeholder="Select countries" />
</SelectTrigger>
<SelectContent>
{countries.map((country) => (
<SelectItem key={country} value={country}>
<div className="flex items-center">
<Checkbox checked={locations.includes(country)} className="mr-
2" />
{country}
</div>
</SelectItem>
))}
</SelectContent>
</Select>
<div className="mt-2">Selected countries: {locations.join(", ")}</div>
</div>
<div>
<Label htmlFor="image">Upload Image</Label>
<Input
id="image"
type="file"
accept="image/*"
onChange={(e) => setImage(e.target.files?.[0] || null)}
required
/>
</div>
<div>
<Label htmlFor="targetAudience">Target Audience</Label>
<Input
id="targetAudience"
value={targetAudience}
onChange={(e) => setTargetAudience(e.target.value)}
placeholder="Describe your target audience"
/>
</div>
<div>
<ReCAPTCHA
sitekey={process.env.NEXT_PUBLIC_RECAPTCHA_SITE_KEY || ""}
onChange={(value) => setRecaptchaValue(value)}
/>
</div>
<div>
<p className="text-sm text-gray-500">
Your ad will be automatically shared on Facebook, Twitter, Instagram,
TikTok, Pinterest, and LinkedIn.
</p>
</div>
<Button type="submit" className="w-full">
Post Ad
</Button>
</form>
)
}

You might also like