JavaScript
// INPUT
const login = document.getElementById("loginInput");
const password = document.getElementById("passwordInput");
const button = document.getElementById("sendButton");
const loginButton = document.getElementById("loginButton");
// FETCH
const url = "https://crudcrud.com/api/ebf57bbd269048e3ac7cacf52f6ac53f/todos";
const dataRender = (array) => {
const getHtml = document.getElementById("userTable");
if (array === undefined) {
console.log("Loading results...");
} else {
let dataList = array.map((item) => {
return `
<div class="users">
<p>${item.login}</p>
<button onclick="deleteRequest('${item._id}')">Delete</button>
</div>
`;
});
getHtml.innerHTML = dataList.join("");
}
};
const fetchData = async () => {
try {
const response = await fetch(url);
const data = await response.json();
dataRender(data);
} catch (error) {
console.error(error);
}
};
fetchData();
// POST_REQUEST
const postRequest = async () => {
const data = {
login: login.value,
password: password.value,
isLogin: false,
};
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
const results = await response.json();
console.log(results.message);
fetchData();
} catch (error) {
console.error(error);
}
};
button.addEventListener("click", () => {
postRequest();
});
// DELETE_REQUEST
const deleteRequest = async (id) => {
try {
const response = await fetch(`${url}/${id}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
});
const results = await response.json();
console.log(results.message);
fetchData();
} catch (error) {
console.error(error);
}
};
//GETLOGGEDIN
const getLoggedIn = async () => {
try {
const response = await fetch (`${url}/getLoggedIn`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
})
const results = await response.json()
console.log(results.message);
}
catch (error) {
console.error(error);
}
}
//UPDATEISLOGIN
const updateIsLogin = async (value) => {
const data = {
isLogin: value
}
try {
const response = await fetch (`${url}/updateIsLogin`, {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
const results = await response.json()
console.log(results.message);
}
catch (error) {
console.error(error);
}
}
// LOGIN_REQUEST
const loginRequest = async () => {
const data = {
login: login.value,
password: password.value,
};
try {
const response = await fetch(`${url}/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
});
const results = await response.json();
console.log(results.message);
if (results.success) {
await updateIsLogin(true);
getLoggedIn()
}
} catch (error) {
console.error(error);
}
};
loginButton.addEventListener("click", () => {
loginRequest();
});