SearchBar.js
import useOptions from "@/src/hooks/useOptions";
import React, { useEffect } from "react";
import { AsyncPaginate } from "react-select-async-paginate";
const SearchBar = () => {
const { promiseOptions, optionsRef, selectedOption, formatOptions } =
useOptions();
return (
<AsyncPaginate
selectRef={optionsRef}
value={selectedOption}
loadOptions={promiseOptions}
loadOptionsOnMenuOpen={true}
placeholder="Search..."
formatOptionLabel={formatOptions}
/>
);
};
export default SearchBar;
useOption.js
import React, { useEffect, useRef, useState } from "react";
const AllCategoriesBtn = () => {
const handleClick = () => (window.location.href = "/all-categories");
return <button onClick={handleClick}> View All Categoties</button>;
};
const sleep = (ms) =>
new Promise((resolve) => {
setTimeout(() => {
resolve(undefined);
}, ms);
});
const useOptions = () => {
const [selectedOption, setSelectedOption] = useState();
const [options, setOptions] = useState([
{ value: "akhlaq", label: "Akhlaq" },
{ value: "amanah", label: "Amanah" },
{ value: "allah", label: "Allah" },
{ value: null, isDisabled: true, label: <AllCategoriesBtn /> },
]);
// Separate state for recent searches
const [recentSearches, setRecentSearches] = useState(
[
{ value: null, isDisabled: true, label: <h1>Recent Searches</h1> },
{
value: "chocolate",
isCached: true,
label: "Chocolate",
},
{
value: "strawberry",
label: "Strawberry",
isCached: true,
},
{
value: "vanilla",
label: "Vanilla",
isCached: true,
},
] || []
);
console.log("Recent Searches ===> ", recentSearches);
const RecentSearch = ({ label, value }) => {
const handleOnClick = () => {
setSelectedOption({ value, label });
};
const handleRemoveClick = (value) => {
setRecentSearches(
recentSearches.filter((option) => option.value !== value)
);
setOptions((prevOptions) =>
prevOptions.filter((option) => option.value !== value)
);
};
return (
<>
<span onClick={handleOnClick}>{label}</span>
<button onClick={() => handleRemoveClick(value)}> Remove</button>
</>
);
};
const promiseOptions = async (inputValue = null) => {
console.log("Typed Option ====> inputValue", inputValue);
if (inputValue) {
await sleep(100);
//! make the API call here
return {
options: options,
};
} else {
return {
options: [...recentSearches, ...options],
};
}
};
const formatOptions = (option) => {
if (!!option.isCached)
return <RecentSearch label={option.label} value={option.value} />;
return option.label;
};
return {
options,
selectedOption,
promiseOptions,
formatOptions,
};
};
export default useOptions;
我想使用删除按钮删除 recentSearches,但它不会在 UI 中更新,即使我的状态(recentSearches)确实得到更新。