Why is my class function not working?

I also use this function in a different location. It works fine there but does not work in this section. It does not show any error on the console. What is the reason of this?

function getAllSearched() {
    let users = Storage.getSearchedUsersFromStorage();
    users.forEach(function (user) {
        ui.addSearchedUserToUI(user)
    })
}

addSearchedUserToUI(userName) {
        let users = Storage.getSearchedUsersFromStorage();
        if (users.indexOf(userName) === -1) {
            const li = document.createElement("li")
            li.className = "list-group-item"
            li.textContent = userName;
            this.lastUsers.appendChild(li)
        }
    }

I think you need to give us a link to your entire codebase. These are taken out of context and there really isn’t enough information to know why they aren’t working. Also, it might help if you explain exactly what you want to do and what it is/isn’t doing.

Thanks for your comment. it’s full codes

class Storage {
    static getSearchedUsersFromStorage() {
        let users;
        if (localStorage.getItem("Searched") === null) {
            users = []
        } else {
            users = JSON.parse(localStorage.getItem("Searched"))
        }
        return users
    }

    static addSearchedUserToStorage(userName) {
        let users = this.getSearchedUsersFromStorage()
        if (users.indexOf(userName) === -1) {
            users.unshift(userName)
        }
        localStorage.setItem("Searched", JSON.stringify(users))
    }

    static clearAllSearchedUsrersFromStorage() {
        localStorage.removeItem("Searched")
    }
}
class UI {
    constructor() {
        this.profilDiv = document.getElementById('profile')
        this.repoDiv = document.getElementById('repos')
        this.lastUsers = document.getElementById('last-users')
        this.inputField = document.getElementById('githubname')
        this.cardBody = document.querySelector('.card-body')
    }

    clearInput() {
        this.inputField.value = '';
    }

    showUserInfo(user) {
        this.profilDiv.innerHTML = `
    <div class="card card-body mb-3">
    <div class="row">
      <div class="col-md-4">
        <a href="${user.html_url}" target = "_blank">
         <img class="img-fluid mb-2" src="${user.avatar_url}"> </a>
         <hr>
         <div id="fullName"><strong>${user.name}</strong></div>
         <hr>
         <div id="bio">${user.bio == undefined ? "Biografi Bilgisi Bulunmuyor." : user.bio}</div>
        </div>
      <div class="col-md-8">
            <button class="btn btn-secondary">
                  Takipçi  <span class="badge badge-light">${user.followers}</span>
            </button>
            <button class="btn btn-info">
                 Takip Edilen  <span class="badge badge-light">${user.following}</span>
              </button>
            <button class="btn btn-danger">
                Repolar  <span class="badge repos-amount badge-light">${user.public_repos}</span>
            </button>
            <hr>
            <li class="list-group">
                <li class="list-group-item borderzero">
                    <img src="images/company.png" width="30px"> <span id="company">${user.company == undefined ? "Ĺžirket Bilgisi Bulunmuyor" : user.company}</span>
                    
                </li>
                <li class="list-group-item borderzero">
                    <img src="images/location.png" width="30px"> <span id = "location">${user.location == undefined ? "Lokasyon Bilgisi Bulunamıyor" : user.location}</a>
                    
                </li>
                <li class="list-group-item borderzero">
                    <img src="images/mail.png" width="30px"> <span id="company">${user.email == undefined ? "Mail Bilgisi Bulunmuyor" : user.email}</span>
                    
                </li>
                
            </div>
               
            
      </div>
</div>
    `
    }

    showError(message) {
        let div = document.getElementById('alertID')
        if (div == null) {
            div = document.createElement('div')
            div.className = "alert alert-danger"
            div.textContent = message
            div.id = "alertID"
            this.cardBody.appendChild(div)
            div.style.marginTop = "1rem"
            document.querySelector('.btn').disabled = true
            document.querySelector('.btn').style.opacity = "1"
        } else {
            div.style.display = "block"
            document.querySelector('.btn').disabled = true
        }
        setTimeout(() => {
            div.style.display = "none"
            document.querySelector('.btn').disabled = false
        }, 2000)
    }

    showRepoInfo(repos, repoAmount) {
        this.repoDiv.innerHTML = ""
        if (repoAmount == 0) {
            this.repoDiv.innerHTML += "Repo Bilgisi Bulunmamaktadır"
        }
        let removed = repos.splice(0, 5)
        removed.forEach(repo => {
            if (repos.length) {
                this.repoDiv.innerHTML += `
                <div class="mb-2 card-body">
                        <div class="row">
                            <div class="col-md-2">
                            <a href="${repo.html_url}" target = "_blank" id = "repoName">${repo.name}</a>
                            </div>
                            <div class="col-md-6">
                                <button class="btn btn-secondary">
                                    Starlar  <span class="badge badge-light" id="repoStar">${repo.stargazers_count}</span>
                                </button>
                                <button class="btn btn-info">
                                    Forklar  <span class="badge badge-light" id ="repoFork">${repo.forks_count}</span>
                                </button>
                            </div>
                    </div>
                    </div>
                    `
            }
        })
    }

    addSearchedUserToUI(userName) {
        let date = new Date().getTime()
        let users = Storage.getSearchedUsersFromStorage();
        if (users.indexOf(userName) === -1) {
            const li = document.createElement("li")
            li.className = "list-group-item"
            li.id = date
            li.textContent = userName;
            this.lastUsers.insertBefore(li, this.lastUsers.firstChild)
        }
    }

    clearAllSearchedFromUI() {
        while (this.lastUsers.firstElementChild !== null) {
            this.lastUsers.removeChild(this.lastUsers.firstElementChild)
        }
    }
}
const githubForm = document.getElementById('github-form')
const nameInput = document.getElementById('githubname')
const clearLastUsers = document.getElementById('clear-last-users')
const lastUsers = document.getElementById('last-users')
const github = new Github()
const ui = new UI()

eventListeners()

function eventListeners() {
    githubForm.addEventListener('submit', getData)
    clearLastUsers.addEventListener('click', clearAllSearched)
    document.addEventListener('DOMContentLoaded', getAllSearched)
}

function getData(e) {
    let userName = nameInput.value.trim().toLowerCase()
    if (userName === '') {
        ui.showError("Lütfen Bir Kullanıcı Adı Giriniz")
    } else {
        github.getGithubData(userName)
            .then(response => {
                if (response.user.message === "Not Found") {
                    ui.showError("Kullanıcı Bulunamadı")
                } else {
                    ui.addSearchedUserToUI(userName)
                    Storage.addSearchedUserToStorage(userName)
                    ui.showUserInfo(response.user)
                    ui.showRepoInfo(response.repo, response.user.public_repos)
                }
            })
            .catch(error => ui.showError(error))
    }
    ui.clearInput()
    e.preventDefault()
}

function clearAllSearched() {
    Storage.clearAllSearchedUsrersFromStorage()
    ui.clearAllSearchedFromUI()
}

function getAllSearched() {
    let users = Storage.getSearchedUsersFromStorage();
    let result = ""
    users.forEach(function (user) {
        result += `<li class="list-group-item">${user}</li>`
    })
    lastUsers.innerHTML = result
}
class Github {
    constructor() {
        this.url = 'https://api.github.com/users/'
    }

    async getGithubData(username) {
        const responseUser = await fetch(this.url + username)
        const responseRepo = await fetch(this.url + username + "/repos")
        const userData = await responseUser.json()
        const repoData = await responseRepo.json()
        return {
            user:userData,
            repo:repoData
        }
    }
}

This is better, but I don’t think it is enough. Can you put the entire project (all files needed to run it) into github and give us a link to the repo so we can actually run your project locally? Also, you haven’t told us what exactly is broken and what is supposed to happen. But we really need to be able to see the entire thing in action.

Problem; The problem with these codes is that I have a function called addSearchedUserToUI in ui.js. I run this function in getData function in api.js and it works fine. But I cannot run this function in getAllSearched function in api.js where I added “DOMContentLoaded” event.

Actually, the ui.addSearchedUserToUI method is executed when DOMContentLoaded is triggered and getAllSearched is executed, it’s just not running the way you intended.

You’ve got some logic issues here. The method ui.addSearchedUserToUI is doing the following check before it adds a user to the list:

if (users.indexOf(userName) === -1) {

This means that it will only add the user to the list if their username is NOT in the users array. The users array is created by getting all of the usernames stored in local storage. So if a username is in local storage then it will not be added to the list. Do you see the logical error here?

The reason ui.addSearchedUserToUI works in getData is because you haven’t added the username to local storage before you call ui.addSearchedUserToUI. If you move the call to ui.addSearchedUserToUI after you add the username to local storage then you will run into the same problem as above.

1 Like

I cannot see a logic error in this section. If there is that element in the list, I prevent it from being added again. There is no problem here. I understand why the function does not work, but I cannot see an error in the part you say there is a logic error.

I guess I don’t understand what you are trying to do here? When does the DOMContentLoaded event fire? When you load/reload the page. So you are calling getAllSearched when you load/reload the page. That function loads all the users saved in local storage and then tries to add them to the list using ui.addSearchedUserToUI. But ui.addSearchedUserToUI won’t add them to the list because of the logic error I pointed out above.

So from what I can tell, when the page is loaded/reloaded, you want to get all the users saved in local storage and add them to the list on the page. Is this really what you want to do?

Yes, If you want, you can show how I can achieve this function.

Well, that would take all of the fun out of it for you :slight_smile:

I think for starters it would be helpful if you renamed some of these functions/methods to make it easier to follow the logic. For example, ui.addSearchedUserToUI, what does “SearchedUser” actually mean? Why do you need to do those local storage checks? Why not just call it addUserToUI and get rid of all the local storage checks. Then you would be able to call addUserToUI from both getAllSearched and getData.

Please give it a proper code base. And please give me a link to the repo so we can actually run your project locally?. After that I will tell you the real issue

The link is to a specific file in the repo but you can easily figure out how to get the repo link from that. If not, here it is:

https://github.com/BerkayAkgurgen/fuzzy-octo-doodle

Since I want to create a list of the last users we searched for, I do this because the same name is not added to the list twice and these last searched people are not deleted when the page is refreshed. If you have run index.html in your local, this list is created under “son aramalar”. “son aralamar” means “Recent Searches” in English

Preventing duplicates is definitely something you want to do but I think it would be easier to follow logically if you didn’t include that logic in the function that adds the user to the list but rather have that as a separate function. Then you would first check to see if the user is already in the list before you call addUserToUI.

I see that you are already checking for duplicates when you add them to local storage, so you are never going to have a duplicate problem when you pull them from storage when the page is loaded. The duplicate problem is going to occur when you click the Ara button. That is when you want to check for duplicates using a function that specifically checks for duplicates. If it isn’t a duplicate, then you can add the user to the UI list and local storage.

Also, there may be some people who deny your app permission to use local storage, so you won’t always have it available. So you need to be able to check for duplicates when you can’t use local storage. This is why the duplicate check needs to be independent of local storage.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.