-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
95 lines (70 loc) · 2.26 KB
/
Copy pathscript.js
File metadata and controls
95 lines (70 loc) · 2.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
const formulario = document.querySelector('#formulario');
const indicador = document.querySelector('#loading');
const alertaErro = document.querySelector('#error-msg');
const botao = document.querySelector('#btn-submit');
const listaPosts = document.querySelector('#posts-container');
const ENDPOINT = 'https://jsonplaceholder.typicode.com/posts';
function exibirLoading(ativo) {
indicador.style.display = ativo ? 'block' : 'none';
alertaErro.style.display = 'none';
}
function exibirErro(texto) {
alertaErro.innerText = `❌ ${texto}`;
alertaErro.style.display = 'block';
}
async function carregarLista() {
exibirLoading(true);
try {
const requisicao = await axios.get(`${ENDPOINT}?_limit=5`);
listaPosts.innerHTML = '';
requisicao.data.forEach(item => {
const card = document.createElement('div');
card.innerHTML = `
<h3>${item.title}</h3>
<p>${item.body}</p>
<hr>
`;
listaPosts.appendChild(card);
});
} catch (erro) {
exibirErro('Não foi possível carregar os posts.');
console.error(erro);
} finally {
exibirLoading(false);
}
}
async function cadastrarPost(dados) {
exibirLoading(true);
try {
const resultado = await axios.post(ENDPOINT, dados);
console.log('Resposta da API:', resultado.data);
alert('Post enviado com sucesso!');
formulario.reset();
} catch (erro) {
exibirErro('Erro ao enviar o post.');
console.error(erro);
} finally {
exibirLoading(false);
}
}
formulario.addEventListener('submit', async function (e) {
e.preventDefault();
botao.disabled = true;
const tituloDigitado = document.querySelector('#titulo').value.trim();
const conteudoDigitado = document.querySelector('#corpo').value.trim();
if (tituloDigitado === '' || conteudoDigitado === '') {
exibirErro('Preencha todos os campos.');
botao.disabled = false;
return;
}
const dadosPost = {
title: tituloDigitado,
body: conteudoDigitado,
userId: 1
};
await cadastrarPost(dadosPost);
botao.disabled = false;
});
window.onload = () => {
carregarLista();
};