Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
React: useState/useEffect - How to collect 10 items in realtime

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>
    )
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda