I have a small text field to filter a object array on my React app but when I type the onChange event skips the first character so it's not filtering the array correctly then when I delete the text it does not delete the first letter I wrote so to remove the filter you must reload the page.
This is my app:
function App() {
const [memes, setMemes] = useState([]);
const [filteredMemes, setFilteredMemes] = useState([]);
// const [filter, setFilter] = useState("");
useEffect(() => {
(async function getData() {
await getMemes();
})();
}, []);
const getMemes = async () => {
const results = await memeService.getMemes();
setMemes(results.data.data.memes);
setFilteredMemes(memes);
}
const handleSearch = (event) => {
const filter = event.target.value;
setFilteredMemes(memes);
filteredMemes.filter((meme) => meme.name.toUpperCase().search(filter.toUpperCase()) >= 0);
}
return (
<>
<Nav handleSearch={handleSearch} />
<Router>
<Switch>
<Route path="/:id/edit" children={<Editor />} />
<Route path="/:id/new" children={<New />} />
<Route path="/">
<div className='container'>
{filteredMemes.map(meme => <Meme key={meme.id} meme={meme} />)}
</div>
</Route>
</Switch>
</Router>
</>
)
}
export default App;
This is the Nav component that contains the input:
import './Nav.css';
const Nav = ({handleSearch}) => {
return (
<div className='nav'>
<input type='text' placeholder='Search' onChange={handleSearch} />
<a href='/'>Home</a>
</div>
)
}
export default Nav;
When I check on console the values that I'm gettin on the handleSearch
function always gets the first letter as white space therefore when you erase the filter the results are no set to the full array.