i am trying to build a simple login page, i've got a really basic form in my html with a button that when pressed is going to pass the data to the javascript. The javascript should validate the data using a json file that i uploaded.
This is the json:
{
"users": [
{
"username": "alice",
"password": "secret"
},
{
"username": "bob",
"password": "p@ssword123"
}
]
This is the class i am going to use as a model
export class User {
constructor(username, password) {
this.username = username;
this.password = password;
}
getName() {
return this.username;
}
getAge() {
return this.password;
}
This is the javascript code:
import { User } from './user.js';
document.addEventListener('DOMContentLoaded', function () {
var submitBtn = document.getElementById('submit-btn');
submitBtn.addEventListener('click', function (event) {
event.preventDefault();
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
fetchUsers()
.then(users => console.log(users))
.catch(error => console.error(error));
});
function fetchUsers() {
fetch('users.json')
.then(response => response.json())
.then(data => {
const users = data.users.map(user => new User(user.username, user.password));
// console.log(users)
return users
})
.catch(error => console.error(error));
The problem is that if i try to log the users in the fetchUser function it logs them, if i try to do it after pressing the button it gives me this error:
Uncaught TypeError: Cannot read properties of undefined (reading 'then') at HTMLButtonElement.
Why is that ?