choc-autocomplete icon indicating copy to clipboard operation
choc-autocomplete copied to clipboard

bug: setting AutocompleteItems dynamically via state does not trigger a re-render, only after refocus rendered

Open kingjulien1 opened this issue 1 year ago • 0 comments

"use client"

import { useDebounce } from "@/lib/hooks/useDebounce"
import { Input, InputGroup, InputLeftElement } from "@chakra-ui/react"
import { AutoComplete, AutoCompleteGroup, AutoCompleteGroupTitle, AutoCompleteInput, AutoCompleteItem, AutoCompleteList, useAutoComplete } from "@choc-ui/chakra-autocomplete"
import { useEffect, useRef, useState } from "react"
import { FaMagnifyingGlass } from "react-icons/fa6"

// auto complete search bar for startups, jobs, profiles in top navbar in main layout
export default function Search() {
  const [search, setSearch] = useState("")
  const debounced_search = useDebounce(search, 500)

  const [users, setUsers] = useState([])
  const [isLoading, setIsLoading] = useState(false)

  function onChange(e) {
    setIsLoading(true)
    setSearch(e.target.value)
  }

  // fetch data from api on search change, debounce search input
  useEffect(() => {
    async function fetchData() {
      setIsLoading(false)
      const users = await (await fetch(`/api/users?name=${debounced_search}&limit=3`)).json()
      setUsers([...users])
    }
    fetchData()
  }, [debounced_search])

  return (
    <InputGroup ml={10} color="gray.200" className="col-span-2">
      <InputLeftElement pointerEvents="none" children={<FaMagnifyingGlass />} />
      <AutoComplete onSelectOption={console.log} isLoading={isLoading} openOnFocus>
        <AutoCompleteInput loadingIcon={<></>} onChange={onChange} value={search} fontWeight="semibold" borderColor="gray.500" placeholder="Search..." w={350} variant="outline" pl={10} />
        <AutoCompleteList mt={2} color="gray.800" borderColor="gray.900" border="2px solid">
          {users.map(user => (
            <AutoCompleteItem key={user._id.toString()} value={user._id.toString()} children={user.name} />
          ))}
        </AutoCompleteList>
      </AutoComplete>
    </InputGroup>
  )
}

Like I said in the title, the AutocompleteItems do not render after the state is set. Only after the input is being refocused and the Autocomplete list reopened, does the Items actually appear.

Is there a way to trigger a rerender manually? or what am I doing wrong here?

kingjulien1 avatar Jan 26 '24 15:01 kingjulien1