Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a search bar #37

Merged
merged 1 commit into from
Oct 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 95 additions & 4 deletions src/components/SearchBar/SearchBar.jsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,98 @@
import React from "react";
import React, { useState, useEffect } from "react";
import { ImSearch } from "react-icons/im";
import { collection, query, onSnapshot } from "firebase/firestore";
import { db } from "@/util/firebase";

function SearchBar() {
return <div>SearchBar</div>;
}
const SearchBar = () => {
const [searchTerm, setSearchTerm] = useState("");
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(false);

const handleSearch = async () => {
setLoading(true);
let q;
if (searchTerm.trim() === "") {
// If the search term is empty, do not perform a search
setProducts([]);
setLoading(false);
return;
}
// Use array-contains for case-insensitive search
q = query(collection(db, "products"));

onSnapshot(q, (snapshot) => {
const productsArray = [];
snapshot.forEach((doc) => {
const data = doc.data();
if (
data.name.toLowerCase().includes(searchTerm.toLowerCase())
) {
productsArray.push({ id: doc.id, ...data });
}
});
setProducts(productsArray);
setLoading(false);
});
};

useEffect(() => {
// Call the search function when searchTerm changes
handleSearch();
}, [searchTerm]);

// Determine if products not found message should be shown
const showNoProductsMessage =
!loading && searchTerm.trim() !== "" && products.length === 0;
const showResultsContainer = products.length > 0;

return (
<div className='relative mx-auto max-w-md'>
<div className='input-wrapper'>
<input
type='text'
placeholder='Search here...'
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
className='w-full border border-gray-300 rounded-full py-2 px-4 pl-8 focus:outline-none'
/>
<div className='absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500'>
<ImSearch />
</div>
</div>

{showResultsContainer && (
<div className='product-container bg-white bg-opacity-80 rounded-lg shadow-lg p-4 absolute left-0 right-0'>
<ul>
{products.map((product) => (
<li key={product.id}>
{product.name
.split(new RegExp(`(${searchTerm})`, "gi"))
.map((text, index) =>
text.toLowerCase() ===
searchTerm.toLowerCase() ? (
<span
key={index}
className='text-blue-500'
>
{text}
</span>
) : (
text
)
)}
</li>
))}
</ul>
</div>
)}

{showNoProductsMessage && (
<p className='text-white bg-gray-500 p-2 rounded'>
No products found.
</p>
)}
</div>
);
};

export default SearchBar;
7 changes: 7 additions & 0 deletions src/components/SearchBar/__test__/SearchBar.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import renderer from "react-test-renderer";

Check warning on line 1 in src/components/SearchBar/__test__/SearchBar.test.js

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

Run autofix to sort these imports!
import SearchBar from "../SearchBar";

it("renders correctly", () => {
const tree = renderer.create(<SearchBar />).toJSON();
expect(tree).toMatchSnapshot();
});
2 changes: 2 additions & 0 deletions src/pages/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import ProductCard from "@/components/ProductCard/ProductCard";

import Layout from "@/layout/Layout";
import { db } from "@/util/firebase";
import SearchBar from "@/components/SearchBar/SearchBar";

export default function HomePage() {
const { t } = useTranslation("common");
Expand All @@ -21,6 +22,7 @@ export default function HomePage() {
return (
<Layout>
<ProductCard />
<SearchBar />
<p>{t("test")}</p>
<div style={{ display: "flex", flexDirection: "row", gap: "20px" }}>
<Link href='/' locale='en'>
Expand Down
2 changes: 1 addition & 1 deletion src/util/firebase.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { initializeApp } from "firebase/app";

Check warning on line 1 in src/util/firebase.js

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

Run autofix to sort these imports!
import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";

Check warning on line 3 in src/util/firebase.js

View workflow job for this annotation

GitHub Actions / ⬣ ESLint

'getAuth' is defined but never used

const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_API_KEY,
Expand All @@ -15,4 +15,4 @@
export const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
// Initialize Firebase Authentication and get a reference to the service
export const auth = getAuth(app);
//export const auth = getAuth(app);
Loading