0

Fetching data and setting it to state is working. But When I try to update that state (filtering) based on the length of input, it is trickier. The problem is that it is not setting the state when the length is less than two.

Why is it not working? And is this a bad practice?

(The commented part is another way of doing that. And it's working.)

Here's the code on codesandbox

1 Answers1

1

You should not be modifying the data which you use to filter because if you do that you are losing the original data as you filter.

A better way is to save the filtered result in a new state variable

Also note that you are not seeing the filtered result until you type 2 characters because you are checking the length of search input

Another thing to note is that you are using the search value set in state immediately after updating it which won't work as state updates are affected by closure.

Check this post for more details: useState set method not reflecting change immediately

Working solution

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

const UsersList = props => {
  const [data, setData] = useState({ records: [] });
  const [search, setSearch] = useState("");
  const [filter, setFilter] = useState({ records: [] });

  useEffect(() => {
    fetch("https://reqres.in/api/users?page=2")
      .then(response => response.json())
      .then(json => {
        setData({ records: json.data });
        setFilter({ records: json.data });
      });
  }, []);
  return (
    <div>
      <label>Enter to search the user</label>
      <br />
      <input
        type="text"
        value={search}
        onChange={e => {
          const searchVal = e.target.value;
          setSearch(searchVal);
          const text = e.target.value.toLowerCase();
          const myRecords = JSON.parse(JSON.stringify(data.records));
          console.log(myRecords);
          if (searchVal.length + 1 >= 2) {
            const newRecords = data.records.filter(
              user =>
                user.first_name.toLowerCase().indexOf(text) >= 0 ||
                user.last_name.toLowerCase().indexOf(text) >= 0 ||
                user.email.toLowerCase().indexOf(text) >= 0
            );
            setFilter({ records: newRecords });
          } else {
            setFilter({ records: data.records });
          }
        }}
      />
      <pre>
        {/* <code>{JSON.stringify(filter, null, 2)}</code> */}
        <code>{JSON.stringify(filter, null, 2)}</code>
      </pre>
    </div>
  );
};

export default UsersList;

Edit FORM VALUES

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400