Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // window.addEventListener('load', onLoad)
- document.querySelectorAll('a').forEach(element => element.classList.remove('active'));
- document.getElementById('home').classList.add('active');
- const catches = document.getElementById('catches');
- const addBtn = document.querySelector('.add')
- const loadBtn = document.querySelector('.load');
- loadBtn.addEventListener('click', loadCatches)
- const formAdd = document.querySelector("#addForm")
- // function onLoad(e) {
- const dataUser = JSON.parse(sessionStorage.getItem('dataUser'))
- catches.innerHTML = '';
- if (dataUser !== null) {
- document.getElementById('user').style.display = "inline-block"
- document.getElementById('guest').style.display = "none"
- document.querySelector("p.email span").textContent = dataUser.email
- addBtn.disabled = false
- loadCatches()
- } else {
- addBtn.disabled = true
- document.getElementById('user').style.display = 'none'
- document.getElementById('guest').style.display = "inline-block"
- }
- // }
- document.querySelector('#main').addEventListener('click', onButtons)
- function onButtons(e) {
- const currentBtn = e.target.textContent
- const id = e.target.id === "" ? e.target.dataset.id : e.target.id
- const currentEl = e.target.parentElement
- if (currentBtn === "Delete") {
- onDelete(id)
- } else if (currentBtn === 'Update') {
- onUpdate(id, currentEl)
- }
- }
- async function onDelete(id) {
- const url = `http://localhost:3030/data/catches/${id}`
- const response = await fetch(url, {
- method: 'DELETE',
- headers: {
- 'Content-Type': 'application/json',
- 'X-Authorization': dataUser.accessToken
- },
- })
- const data = await response.json()
- loadCatches()
- }
- async function onUpdate(id, currentEl) {
- let [angler, weight, species, location, bait, captureTime] = currentEl.querySelectorAll('input')
- const url = `http://localhost:3030/data/catches/${id}`
- const body = JSON.stringify({
- angler: angler.value,
- weight: Number(weight.value),
- species: species.value,
- location: location.value,
- bait: bait.value,
- captureTime: Number(captureTime.value)
- })
- try {
- const response = await fetch(url, {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- 'X-Authorization': dataUser.accessToken
- },
- body,
- })
- const data = await response.json()
- if (!response.ok) throw new Error(data.message)
- } catch (e) {
- alert(e.message)
- }
- loadCatches()
- }
- formAdd.addEventListener('submit', (e) => {
- e.preventDefault();
- const formData = new FormData(e.target);
- onAdd([...formData.entries()].reduce((a, [k, v]) => Object.assign(a, { [k]: v }), {}))
- e.target.reset()
- });
- async function onAdd(body) {
- // console.log(body)
- const url = `http://localhost:3030/data/catches`
- try {
- if (Object.values(body).some(x => x === "")) throw new Error("Some fields are empty")
- const response = await fetch(url, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-Authorization': `${dataUser.accessToken}`
- },
- body: JSON.stringify(body)
- })
- const data = await response.json()
- console.log(data)
- if (!response.ok) throw new Error(data.message)
- loadCatches()
- } catch (e) {
- alert(e.message)
- }
- }
- async function loadCatches() {
- const url = `http://localhost:3030/data/catches`
- const response = await fetch(url)
- const data = await response.json()
- console.log(data)
- document.getElementById('catches').replaceChildren(...data.map(createInfo));
- }
- function createInfo(data) {
- let isDisabled = (dataUser && data._ownerId === dataUser.id) ? false : true
- const divCatches = createElements('div', { class: 'catch' },
- createElements('label', {}, 'Angler'),
- createElements('input', { type: 'text', class: 'angler', value: data.angler, disabled: isDisabled }),
- createElements('label', {}, 'Weight'),
- createElements('input', { type: 'text', class: 'weight', value: data.weight, disabled: isDisabled }),
- createElements('label', {}, 'Species'),
- createElements('input', { type: 'text', class: 'species', value: data.species, disabled: isDisabled }),
- createElements('label', {}, 'Location'),
- createElements('input', { type: 'text', class: 'location', value: data.location, disabled: isDisabled }),
- createElements('label', {}, 'Bait'),
- createElements('input', { type: 'text', class: 'bait', value: data.bait, disabled: isDisabled }),
- createElements('label', {}, 'Capture Time'),
- createElements('input', { type: 'text', class: 'captureTime', value: data.captureTime, disabled: isDisabled }),
- createElements('button', { class: "update", id: data._id, disabled: isDisabled }, "Update"),
- createElements('button', { class: "delete", id: data._id, disabled: isDisabled }, "Delete"),
- )
- return divCatches
- }
- document.getElementById('logout').addEventListener('click', async (e) => {
- const url = `http://localhost:3030/users/logout`
- const response = await fetch(url)
- const data = await response.json();
- sessionStorage.clear();
- window.location = '/src/index.html'
- });
- function createElements(type, atr, ...content) {
- const element = document.createElement(type)
- for (const at in atr) {
- if (at === "class") {
- element.classList.add(atr[at])
- } else if (at === 'disable') {
- element.disabled = atr[at]
- } else {
- element[at] = atr[at]
- }
- }
- for (let el of content) {
- if (typeof el == 'string' || typeof el === 'number') {
- el = document.createTextNode(el);
- }
- element.appendChild(el)
- }
- return element;
- }
- // function header(method, body) {
- // const accessToken = dataUser.accessToken
- // return {
- // method: `${method}`,
- // headers: {
- // "Content-Type": "application/json",
- // "X-Authorization": `${dataUser.accessToken}`
- // },
- // body: JSON.stringify(body)
- // }
- // }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement