I am trying to get 10 usernames back when I type a keystroke. For now it only gives me a Username back if the username is exactly in the jsonplaceholder list. So when i type "Karia" nothing comes back until I type "Karianne"
So for example if the Input gets the first letter "A", I want to give back the first 10 Items which are matching from the jsonplaceholder list. If I put in an "R", after that, so its "Ar" I want to get back the first 10 matching "Ar" usernames, like Aron, Ariel, Aria, etc.
Does someone have an Idea?
export const Search = () => {
const [user, setUser] = useState(null);
const [searchQuery, setSearchQuery] = useState("")
useEffect(() => {
if (searchQuery.length > 0) {
const fetchFunc = async () => {
const response = await fetch(`https://jsonplaceholder.typicode.com/users?username=${searchQuery}`)
const resJSON = await response.json();
setUser(resJSON[0]);
};
fetchFunc();
}
}, [searchQuery]);
return (
<Flex className={styles.search__container}>
<Flex className={styles.search__elements}>
<InputGroup className={styles.search__input}>
<InputRightElement
className={styles.search__inputElements}
children={<RiSearchLine className={styles.search__icon} />} />
<Input
className={styles.search__users}
type='search'
placeholder='Search'
onChange={event => setSearchQuery(event.target.value)}
/>
{user ? (
<div>
<h3>{user['name']}</h3>
<h3>{user['username']}</h3>
<h3>{user['email']}</h3>
</div>
) : (
<p>No user found</p>
)}
</InputGroup>
</Flex>
</Flex>
)
}
CodePudding user response:
The main limitation here is on the API side. Your API should supply you with the similar names. If it doesn't, then you can't do much.
CodePudding user response:
Maybe the API provides a way to retrieve users with partial names (but I doubt it would be the case). Otherwise, you can retrieve all users once,and simply display the one that fits your requirements, every time you write something.
To sum up: When your component is mounted (at the beginning), fetch all users, and store them. You will perform this API call only once.
Then, every time you write something, just take the 10 users that have a name that include what you wrote.
CodePudding user response:
Ideally, this should be handled by the API, and you should be concerned about when to trigger or re-trigger the API call.
API gets you a list of names, you slice a set of 10 from the list of names and set it in users, and then simply map them in your UI.
Also, you could maybe further optimise the function debouncing the API call.
