Skip to content

Commit

Permalink
Add link validation to SearchBar component
Browse files Browse the repository at this point in the history
  • Loading branch information
arka8038 committed Jun 17, 2024
1 parent 04f73b7 commit dec20d1
Showing 1 changed file with 48 additions and 3 deletions.
51 changes: 48 additions & 3 deletions components/SearchBar.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,63 @@
'use client'

import { FormEvent, useState } from 'react'

const isValidAmazonProductUrl = (url: string) => {
try {
const parsedUrl = new URL(url)
const hostname = parsedUrl.hostname

if (
hostname.includes('amazon.com') ||
hostname.includes('amazon.') ||
hostname.endsWith('amazon.com')
) {
return true
}
} catch (error) {
return false
}
return false
}

const SearchBar = () => {
const handleSubmit = () => {}
const [searchPrompt, setSearchPrompt] = useState('')
const [isLoading, setIsLoading] = useState(false)

const handleSubmit = (event: FormEvent<HTMLFormElement>) => {
event.preventDefault()

const isValidLink = isValidAmazonProductUrl(searchPrompt)

if (!isValidLink) return alert('Please provide a valid Amazon product link')

try {
setIsLoading(true)

//scrape the product page
} catch (error) {
console.error(error)
} finally {
setIsLoading(false)
}
}

return (
<form className="flex flex-wrap gap-4 mt-12" onSubmit={handleSubmit}>
<input
type="text"
value={searchPrompt}
onChange={(e) => setSearchPrompt(e.target.value)}
placeholder="Enter product link"
className="searchbar-input"
/>

<button type="submit" className="searchbar-btn">
Search
<button
type="submit"
className="searchbar-btn"
disabled={searchPrompt === ''}
>
{isLoading ? 'Searching...' : 'Search'}
</button>
</form>
)
Expand Down

0 comments on commit dec20d1

Please sign in to comment.