Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!