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;
