0
votes

I want to filter my state (array of objects) based on an input value but I am pretty sure I am doing something very wrong and violating a core concept/rule in React. It is filtering my state when I am typing, however, If I want to get back to the original state (input value is empty), I cannot because I already mutated the array? I am trying to copy the original state to another array and process it, but the result is the same.

What is the correct way to filter the state based on this example?

const App = () => {
  const [persons, setPersons] = useState([
    { name: 'Arto Hellas', number: '040-123456' },
    { name: 'Ada Lovelace', number: '39-44-5323523' },
    { name: 'Mary Poppendieck', number: '39-23-6423122' }
  ]);
  const [name, setName] = useState('');


  const handleFilterName = event => {
    setName(event.target.value);
    if (name !== '') {
      const filteredPersons = persons.filter(person =>
        person.name.toLowerCase().includes(name.toLowerCase())
      );
      setPersons(filteredPersons);
    }
  };

...

 return (
      <div>
        Filter: <input onChange={handleFilterName} value={name} />
      </div>
...
1
Keep a separate reference, e.g. originalPeople. - jonrsharpe

1 Answers

0
votes

I would probably write it like this:

  1. handleFilterName only sets the name.
  2. When you are going to show the filtered list, at that point (e.g. in the render), calculate filteredPersons and show them. Do not alter the persons list.
  3. Then, if you reset name, you will still have your full list.

This is a working example:

function App() {
  const persons = [
    { name: "Arto Hellas", number: "040-123456" },
    { name: "Ada Lovelace", number: "39-44-5323523" },
    { name: "Mary Poppendieck", number: "39-23-6423122" }
  ];
  const [name, setName] = useState("");

  const handleFilterName = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };

  const filteredPersons =
    name === ""
      ? persons
      : persons.filter(person =>
          person.name.toLowerCase().includes(name.toLowerCase())
        );

  return (
    <div>
      Filter: <input onChange={handleFilterName} value={name} />
      <ul>
        {filteredPersons.map(person => (
          <li>
            {person.name}: {person.number}
          </li>
        ))}
      </ul>
    </div>
  );
}