Query

Search Query

import { collection, doc, getDoc, getDocs, limit, query, startAt, where } from "firebase/firestore";
import { db } from "../../Configs/firebase";
import React, { useEffect, useState } from 'react'

 
 function AppBarSearch() {
    const [inputSearch, setInputSearch] = useState("");
    const [detailProject, setDetailProject] = useState([]);


     const getInputProject = async () => {
        if (inputSearch !== undefined) {
          try {
            const ref = collection(db, "nft721-contract");
            const q = query(ref,
            where("address", "==", inputSearch ), // query base on address
            limit(15) 
            );
          let result = [];
          const querySnapshot = await getDocs(q);
          querySnapshot.forEach((doc) => {
            result.push(doc.data())
          });
          setDetailProject(result);
          if (!result.length){ // if not found
            const ref = collection(db, "nft721-contract");
            const q = query(ref,
            where("symbol", ">=", inputSearch ),   // symbol = query base on symbol
            where("symbol", "<=", inputSearch+'\uf8ff'), // 'uf8ff' = to search only 2 or any letter
            limit(15) 
            );
          let result = [];
          const querySnapshot = await getDocs(q);
          querySnapshot.forEach((doc) => {
            result.push(doc.data())
          });
          setDetailProject(result);
          if(!result.length){
            const ref = collection(db, "nft721-contract");
            const q = query(ref,
            where("name", ">=", inputSearch ), // query base on name
            where("name", "<=", inputSearch+'\uf8ff'),
            limit(15) 
            );
          let result = [];
          const querySnapshot = await getDocs(q);
          querySnapshot.forEach((doc) => {
            result.push(doc.data())
          });
          setDetailProject(result);
          }
          }
          } catch (error) {
            console.log(error, 'ini error')
          }
      }};
      
      useEffect(() => {
        getInputProject();

        return () => {
            setDetailProject([])
        };

      }, [inputSearch]);

  
  return (
    <Box w="100%" height="100vh" paddingTop={10} flexDirection="column">
    <Box m="2" width="full">
      <Input
        variant="flushed"
        placeholder="Search wallet address / ENS"
        size="sm"
        onChange={(e) => setSearch(e.target.value)}
      />
    </Box>
    {console.log(detailProject, 'this data')}
  </Box>
  )
}

export default AppBarSearch

Last updated

Was this helpful?