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

166
Views
Why doesn't my useState array get emptied?

My useState:

const [valuesToSearchFor, setValuesToSearchFor] = useState([]);

I have the following search input field with an onChange:

onChange={() => {
  setValuesToSearchFor(
  valuesToSearchFor.includes(value)
    ? valuesToSearchFor.filter(val => val !== value)
    : [...valuesToSearchFor, value]
  );
}}

This changes some data on my page like so:

{data.elements.filter((val) => {
  if(valuesToSearchFor.includes(val.name.toLowercase()){
      return val
  }
}

The only issue is when I delete the input field, it doesn't reflect in the array. Question How can I empty out valUesToSearchFor so another search can be typed out in the input?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Hard to say without seeing more of your code, but you should destructure your filtered valuesToSearchFor. Otherwise you're trying to modify a state prop directly

onChange={(e) => {
  const value = e.target.value;
  setValuesToSearchFor(
    valuesToSearchFor.includes(value)
    ? [...valuesToSearchFor.filter((val) => val !== value)]
    : [...valuesToSearchFor, value]
  );
}}

As @Amiratak88 points out, this is going to push a new value to your array on every keystroke.

Again, not sure what you're trying to do, but you might opt to use buttons that update/reset your state.

const MyComponent = () => {
  const [searchValue, setSearchValue] = useState("");
  const [valuesToSearchFor, setValuesToSearchFor] = useState([]);

  return (
    <>
      <input
        onChange={(e) => {
          setSearchValue(e.target.value);
        }}
      />
      <button
        onClick={(e) => {
          e.preventDefault();
          // update valuesToSearchFor with all unqiue values, including the current searchValue
          setValuesToSearchFor([...new Set([...valuesToSearchFor, searchValue])]);
        }}
      >
        Search
      </button>
      <button
        onClick={(e) => {
          e.preventDefault();
          setValuesToSearchFor([]);
        }}
      >
        Reset
      </button>
    </>
  );
};


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!