API search in javascript to return filtered list only

  api, fetch, filter, javascript

I am trying to make a filtered API search and only display the data(users) that has been filtered. However my search seems to return all the data and not just the data that has been filtered out. I can see the right data in the console log but can’t seem to figure out how to get it to render on display.
For example, if I search for janet, I can see all the data that contains the name janet when I console log it but on display it still displays all the users. What am I doing wrong? Thanks

const UserList = document.getElementById('userList');
const searchBar = document.getElementById('searchBar'); 
let data = []; 

searchBar.addEventListener('keyup', (e) => {
    e.preventDefault();
    const searchString = e.target.value;
   
    console.log(e.target.value)
    const filteredUsers = data.data.filter((user) => {
        return (
            user.first_name.includes(searchString) ||
            user.email.includes(searchString)
        );
    });
    console.log(filteredUsers)
    displayUsers(filteredUsers); 
});

const loadUsers = async () => {
    try {
        const res = await fetch('https://reqres.in/api/users');
        data = await res.json();
        displayUsers(data);
        console.log(data)
    } catch (err) {
        console.error(err);
    }
};

const displayUsers = (users) => {
    const htmlString = data.data
        .map((user) => {
            return `
            <li class="user">
                <h2>${user.first_name}</h2>
                
            </li>
        `;
        })
        .join('');
    userList.innerHTML = htmlString;
};

loadUsers();

Source: Ask Javascript Questions

LEAVE A COMMENT