Home > Back-end >  Why doesn't my useState array get emptied?
Why doesn't my useState array get emptied?

Time:03-09

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?

CodePudding user response:

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>
    </>
  );
};


  • Related