3

我的 Google Books 克隆应用程序有一个用户提交他们输入的内容query,然后显示响应data

我想实现Downshift的搜索自动完成功能,以便作为他们的user类型query,列出与他们当前匹配的建议的下拉列表query。单击下拉建议列表中的列表项应更新输入查询,然后获取该data查询query我希望有与Google 图书相同的行为

文档中示例中的数据Downshift是硬编码的。就我而言,datafetch.

我想我需要创建一个建议对象并定义useCombobox逻辑以获取每个输入更改的建议。然后分配handleBookFetch给下拉列表的项目' onClick。通过这次尝试,我收到了TypeErrorCannot read property 'length' of undefined.

我在试图弄清楚如何在我的实例中使用它时遇到了麻烦。当用户在输入中键入查询时,如何获取建议,然后使用单击的建议更新查询值并获取单击的建议的查询?代码沙盒

const [query, setQuery] = useState("");
const [books, setBooks] = useState({ items: [] });
const [suggestions, setSuggestions] = useState({ suggestionItems: [] });

useCombobox({
    suggestions: suggestions,
    onInputValueChange: ({ inputValue }) => {
      const fetchSuggestions = async () => {
        try {
          const result = await axios.get(`${API_BASE_URL}?q=${query}`);
          setSuggestions(result.data);
        } catch (isError) {
          setIsError(true);
        }
      };
      fetchSuggestions();
      setSuggestions(
        suggestions.suggestionItems.filter((suggestionItem) =>
          suggestionItem.toLowerCase().startsWith(inputValue.toLowerCase())
        )
      );

const handleBookFetch = (event) => {
  const fetchBooks = async () => {
    try {
      const result = await axios.get(`${API_BASE_URL}?q=${query}`);
      setBooks(result.data);
    } catch (isError) {
      setIsError(true);
    }
  };
  fetchBooks();
};

<form onSubmit={handleBookFetch}>
  <div className={comboboxStyles} {...getComboboxProps()}>
    <input
      type="text"
      value={query}
      onChange={(event) => setQuery(event.target.value)}
      {...getInputProps()}
    />
    <button
      type="button"
      {...getToggleButtonProps()}
      aria-label="toggle menu"
    >
      &#8595;
    </button>
    <button type="submit">Search</button>
  </div>

  <ul {...getMenuProps()} style={menuStyles}>
    {isOpen &&
      suggestions.suggestionItems.map((book, index) => (
        <li
          style={
            highlightedIndex === index
              ? { backgroundColor: "#bde4ff" }
              : {}
          }
          key={`${book}${index}`}
          onClick={handleFetchBook}
          {...getItemProps({ book, index })}
        >
          {book.volumeInfo.title}
        </li>
      ))}
  </ul>
</form>
4

0 回答 0