1

Using ReactJS, Firestore - Firebase v9.

I have an autocomplete search bar on my web, built with just pure React. The question that I am trying to solve for at least one month is, if I can make this autocomplete input work with Firestore - (user type E.g 'elepha', auto suggestion appears with offer with word elephant - this is what I coded, and with same case, user will click on the suggestion of elephant, and this word elephant will be send to Firestore.)

Cuz there is not any solution on internet, I wonder, if my question is even possible to make, or not.

My simple autocomplete bar code - (animals_data stands for file with animals names) and I tried to add onClick={pleaseSend} which is basic addDoc function, but when I click on the suggestion, in Firestore will only appear blank input "".

<SearchBar data={animals_data} />

And the filtering code:

function SearchBar({ placeholder, data }) {
  const [filteredData, setFilteredData] = useState([]);
  const [wordEntered, setWordEntered] = useState("");
  const [newAnswer, setAnswer] = useState("")
  const [users, setUsers] = useState([]);
  
  const usersCollectionRef = collection(db, "Answers")
  const createUser = async () => {
    await addDoc(usersCollectionRef, {name: newAnswer}).then(()=>{
      window.location.reload()
    }).catch((err)=>{
      console.log(err)
    })
  };  


  const handleFilter = (event) => {
    const searchWord = event.target.value;
    setWordEntered(searchWord);
    const newFilter = data.filter((value) => {
      return value.full_name.toLowerCase().includes(searchWord.toLowerCase());
    });

    if (searchWord === "") {
      setFilteredData([]);
    } else {
      setFilteredData(newFilter);
    }
  };

  const clearInput = () => {
    setFilteredData([]);
    setWordEntered("");
  };

  return (
    <div className="search">
      <div className="searchInputs">
        <input
          type="text"
          placeholder={placeholder}
          value={wordEntered}
          onChange={handleFilter}
        />
        
      </div>
      {filteredData.length !== 0 && (
        <div className="dataResult">
          {filteredData.slice(0, 15).map((value, key) => {
            return (
              <a className="dataItem" onClick={createUser} target="_blank">
                <p>{value.full_name} </p>
              </a>
            );
          })}
        </div>
      )}
    </div>
  );
}

export default SearchBar;

EDIT 1: added code screenshots enter image description here


enter image description here web:enter image description here

Thank you very much for reading.

Simon
  • 63
  • 9
  • @HittuDesai first of all, thank you very much... I clearly do not know, how to do it, I have changed to basic input field, and then try to value={searchBar}, how it can the input have the same value as the searchBar tag? Sorry for my questions... – Simon Jul 25 '22 at 10:28

1 Answers1

1

after analyzing your code, I notice that you don't update the value newAnswer using its setter. Therefore, you should use the setter to update the state on user click and then add the firestorm document. You can do that by either using a button/unmodifiable input field in instead of an anchor tag to store the value of each option, then use this value inside the click handler to update the state and then use a useEffect to update firestore every time the state changes. Let me know if you need help with some code. Please post it below your original question as an edit without changing it.

HittuDesai
  • 341
  • 2
  • 7
  • I can only add comments to my own answer. The way you will do it is, you will render an input element with a value prop set to your animalName and make it unmodifiable. Now to each of those fields, you add an onClick handler with its event as parameter through which you can access the stored value as event.target.value. After you have that, you can store it inside the state using your setter. – HittuDesai Jul 25 '22 at 11:23
  • Ah, sorry - lesson learned. So I have to create one input for each name? I have 1352 names, it would not fit on the website. Do I understand correctly? Thank you. – Simon Jul 25 '22 at 11:33
  • All in all, you must create something on which you can click that will allow you to store its value somehow, so that you can make use of it in its handler, That can be a button, input, or anything else you prefer. But since you have a lot of suggestions, maybe, you can make sure that the suggestions are spit out only after X(lets say 3) number of characters are entered into the textfield. This way, your search results will be narrowed down heavily and the UI won't look humongous. – HittuDesai Jul 25 '22 at 15:45
  • I forgot to add into question the button code, . But since I have web refresh function after user clicks on the suggestion, I do not use it. Good idea for 'three word appear' . It is now working correctly, but I cant really figure out, why it just stant blank input, instead of suggestion that user clicked in.. – Simon Jul 25 '22 at 18:25
  • Can you attach a screenshot of the current UI that you have with how the suggestions show up and jsx related to it. That’ll be helpful! – HittuDesai Jul 26 '22 at 04:55
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/246765/discussion-between-simon-and-hittudesai). – Simon Jul 26 '22 at 07:24