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

108
Visualizações
how to solve asynchronous behaviour in search Box react

so im trying to implement a search box with useState and useEffect. we have an array of objects and want to filter it according to our search term. here is my implementation:

import React, {useEffect, useState} from "react";

const array = [
    { key: '1', type: 'planet', value: 'Tatooine' },
    { key: '2', type: 'planet', value: 'Alderaan' },
    { key: '3', type: 'starship', value: 'Death Star' },
    { key: '4', type: 'starship', value: 'CR90 corvette' },
    { key: '5', type: 'starship', value: 'Star Destroyer' },
    { key: '6', type: 'person', value: 'Luke Skywalker' },
    { key: '7', type: 'person', value: 'Darth Vader' },
    { key: '8', type: 'person', value: 'Leia Organa' },
];

let available = []


const Setup = () => {
    const [state, setState] = useState('');
    
    useEffect(() => {
        available = array.filter(a => a.value.startsWith(state));
    },[state])

    const show = state ? available : array;

    return <>
        <input value={state} onChange={e => setState(e.target.value)} type="text" className="form"/>
        {show.map(a => {
            return <Data id={a.key} key={parseInt(a.key)} value={a.value} type={a.type}/>
        })}
    </>
}

const Data = (props) => {
    return <>
    <div>
        <p>{props.value}</p>
    </div>

    </>
}



export default Setup;

the problem starts when we give our search box a valid search term(like 'T'). i expect it to change the output accordingly(to only show 'Tatooine') but the output does not change. meantime if you add another character to search term(like 'a' which would set our search term to 'Ta') it will output the expected result. in the other words, search term is not applied synchronously. do you have any idea why is that

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The useEffect hook is triggered when the component mounts, rerenders or unmounts. In your case, the change of the search field causes a rerender because of the change of the state. This results in your useEffect triggering after the state change and is too late for what you need.

If you type "Ta" into your field, you'll see it works, but it appears as if the search is one step behind.

You can simply remove the use of useEffect and filter when you render. This means you can also remove the whole logic around the available and show variables:

const Setup = () => {
  const [state, setState] = useState("");

  return (
    <>
      <input
        value={state}
        onChange={(e) => setState(e.target.value)}
        type="text"
        className="form"
      />
      {array
        .filter((a) => a.value.startsWith(state))
        .map((a) => (
          <Data
            id={a.key}
            key={parseInt(a.key, 10)}
            value={a.value}
            type={a.type}
          />
        ))}
    </>
  );
};

There is some good information in the Using the Effect Hook docs.

about 4 years ago · Juan Pablo Isaza Relatório

0

You just add toLowerCase mehtod to your filter function. just like this :

import React, { useEffect, useState } from "react";

const array = [
  { key: "1", type: "planet", value: "Tatooine" },
  { key: "2", type: "planet", value: "Alderaan" },
  { key: "3", type: "starship", value: "Death Star" },
  { key: "4", type: "starship", value: "CR90 corvette" },
  { key: "5", type: "starship", value: "Star Destroyer" },
  { key: "6", type: "person", value: "Luke Skywalker" },
  { key: "7", type: "person", value: "Darth Vader" },
  { key: "8", type: "person", value: "Leia Organa" }
];

let available = [];

const Setup = () => {
  const [state, setState] = useState("");

  useEffect(() => {
    available = array.filter((a) => a.value.toLowerCase().startsWith(state));
  }, [state]);

  const show = state ? available : array;

  return (
    <>
      <input
        value={state}
        onChange={(e) => setState(e.target.value)}
        type="text"
        className="form"
      />
      {show.map((a) => {
        return (
          <Data
            id={a.key}
            key={parseInt(a.key)}
            value={a.value}
            type={a.type}
          />
        );
      })}
    </>
  );
};

const Data = (props) => {
  return (
    <>
      <div>
        <p>{props.value}</p>
      </div>
    </>
  );
};

export default Setup;

and here is the working example : here

about 4 years ago · Juan Pablo Isaza Relatório

0

You can simply just pull out useEffect.

import React, { useState } from 'react';

const array = [
    { key: '1', type: 'planet', value: 'Tatooine' },
    { key: '2', type: 'planet', value: 'Alderaan' },
    { key: '3', type: 'starship', value: 'Death Star' },
    { key: '4', type: 'starship', value: 'CR90 corvette' },
    { key: '5', type: 'starship', value: 'Star Destroyer' },
    { key: '6', type: 'person', value: 'Luke Skywalker' },
    { key: '7', type: 'person', value: 'Darth Vader' },
    { key: '8', type: 'person', value: 'Leia Organa' },
];

let available = [];

const Setup = () => {
    const [state, setState] = useState('');

    available = array.filter(a => a.value.startsWith(state));

    const show = state ? available : array;

    return (
        <>
            <input
                value={state}
                onChange={e => setState(e.target.value)}
                type='text'
                className='form'
            />
            {show.map(a => {
                return (
                    <Data
                        id={a.key}
                        key={parseInt(a.key)}
                        value={a.value}
                        type={a.type}
                    />
                );
            })}
        </>
    );
};

const Data = props => {
    return (
        <>
            <div>
                <p>{props.value}</p>
            </div>
        </>
    );
};

export default Setup;

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