Good afternoon guys, I need to create an application that, when clicking a button, retrieves data from an api and renders the screen inside a table. Each row in this table has a button to "favor" the row, which is nothing more than saving your content in the localStorage.
Until this part I was able to do it, but I can not make sure that the elements I have saved persist on the screen even after giving a reload on the page. What should I do to achieve this? Here is the code:
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Fetch API - HTTP Requests</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
td{
border: 1px solid #999999;
padding: 3px;
}
td button{
height: 18vh;
}
.header{
text-align: center;
}
.header button{
width: 40%;
height: 8vh;
background-color: #212121;
color: #fff;
border-radius: 15px;
}
button:focus{
outline: none;
}
</style>
</head>
<body>
<div class="header">
<h1>Desafio.js 2</h1>
<button id="getPosts" type="button">Buscar dados na API</button>
<button id="eraser" type="button">Excluir todos, excerto favoritos</button>
</div>
<table id="output">
<script src="script.js"></script>
</table>
<hr>
</body>
</html>
Javascript:
//variables
var obj;
fetch('https://jsonplaceholder.typicode.com/posts')
.then(res => res.json())
.then(data => obj = data)
.then(() => console.log(obj)) //debug
//eventListeners
document.getElementById('getPosts').addEventListener('click', getPost);
//functions
function getPost(){
fetch('https://jsonplaceholder.typicode.com/posts')
.then((res) => res.json())
.then((data) => {
let output = '<h3>Postagens</h3>' + '<td>User ID</td><td>ID</td><td>Title</td><td>Body</td><td>Favoritos</td>'
data.forEach(function(post){
output+= '
<tr>
<td>${post.userId}</td>
<td>${post.id}</td>
<td>${post.title}</td>
<td>${post.body}</td>
<td><button type="button" class="favorite" data-id="${post.id}">Favoritar!</button></td>
</tr>
'
})
document.getElementById('output').innerHTML = output;
initListener();
})
}
function initListener(){
let favorites = document.querySelectorAll('.favorite');
let favLength = favorites.length;
favorites.forEach((favorites) =>{
favorites.addEventListener('click', (event) => {
let keyID = event.target.dataset.id;
let favObj = obj[(keyID)-1];
console.log('Button clicked with id of: ${event.target.dataset.id}') //debug; passado o param., acessei o alvo que é a data setada (data-id) e a identificação que dei a essa data (-id)
localStorage.setItem(keyID, JSON.stringify(favObj));
let dataObj = JSON.parse(localStorage.getItem(keyID));
console.log('localStorage tamanho: ' + localStorage.length) //debug
})
})
console.log(output)
console.log('Quantidade de rows: ' + favorites.length);
}