Bjork
Bjork

Reputation: 57

API search in javascript to return filtered list only

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?

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();

Upvotes: 0

Views: 85

Answers (2)

Daniel B.
Daniel B.

Reputation: 181

On displayUsers function you are mapping on data.data variable. You should use users.map.

Upvotes: 1

ozerodb
ozerodb

Reputation: 551

This might not be the problem, but you are defining UserList at the top and then using userList at the bottom, small typo maybe?

Upvotes: 0

Related Questions