0

Ok so i have to run registration form against jsonplaceholder users to see if there are duplicate and return "Registration Complete" or "User Already Exists"

if(isValid)
    {

        fetch('https://jsonplaceholder.typicode.com/users/')
        .then(response => response.json())
        .then(users => {
        users.forEach(function(user){
                if(user.username==usersname){
                isValid=false;
                }
            });
        });
        
        
        if(isValid){
            var x = document.getElementsByClassName("success");
            x[0].innerHTML="";
            var y = document.getElementsByClassName("errExist");
            y[0].innerHTML="Registration Complete";
        }else{
            var x = document.getElementsByClassName("errExist");
            x[0].innerHTML="";
            var y = document.getElementsByClassName("success");
            y[0].innerHTML="User Already Exists";
        }
    }

This is the code, but for whatever reason isValid always remains "True" despite me knowing that it enters the if(user.username==usersname). It always shows "Registration Complete". Can someone explain why that is and how to fix it?

2 Answers2

1

fetch is an async function. While it runs, the rest of the code runs as well. Hence, isValid is actually updated after checking the condition already.

You should either move the if condition to be inside the last .then inside fetch or use a Promise.

amit177
  • 56
  • 1
  • 3
0

You need to include the dom code inside .then(), otherwise, it is executed before you getting fetch request (async operation)

if (isValid) {
  fetch("https://jsonplaceholder.typicode.com/users/")
    .then((response) => response.json())
    .then((users) => {
      users.forEach(function (user) {
        if (user.username == usersname) {
          isValid = false;
        }
      });

      if (isValid) {
        var x = document.getElementsByClassName("success");
        x[0].innerHTML = "";
        var y = document.getElementsByClassName("errExist");
        y[0].innerHTML = "Registration Complete";
      } else {
        var x = document.getElementsByClassName("errExist");
        x[0].innerHTML = "";
        var y = document.getElementsByClassName("success");
        y[0].innerHTML = "User Already Exists";
      }
    });
}
Nader Alfakesh
  • 201
  • 2
  • 5