I am developing a website for a project. The main function of this website is to allow registered users to create, edit, and share wish lists that they create. This website is made using nodejs, handlebars as a view engine, and html/js for code. It uses mysql to log user info and list items. My list creation screen allows possibly infinite inputs by creating a new input field on the press of a button. It works as follows:
addBtn.addEventListener('click', function () {
const item_contianer = document.createElement('div');
item_contianer.className = 'item-container';
const item = document.createElement('input');
item.type = 'text';
item.id = 'item';
item.name = 'item';
item.placeholder = 'Insert Item Here';
item.required = 'true';
const removeBtn = document.createElement('button');
removeBtn.id = 'remove';
removeBtn.innerHTML = 'X';
list.appendChild(item_contianer);
item_contianer.appendChild(item);
item_contianer.appendChild(removeBtn);
removeBtn.addEventListener('click', function () {
this.parentElement.remove();
});
});
When I save this info in my database, it is saved as an string in the format of an array ([“Item 1″,”Item 2″,”Item 3”] by the following code:
exports.create = async (req, res) => {
const decoded = await promisify(jwt.verify)(req.cookies.jwt, process.env.JWT_SECRET);
const listName = req.body.list_name;
**const listItems = JSON.stringify(req.body.item);**
db.query('INSERT INTO userlists SET ?', {id: decoded.id, listName: listName, listItems: listItems}, (err, results) => {
if(err) {
console.log(err);
} else {
return res.status(200).redirect('../view');
}
});
}
To access this info I read it from the table and send a JSON object to the page:
exports.view = async (req, res, next) => {
if(req.cookies.jwt) {
try {
const decoded = await promisify(jwt.verify)(req.cookies.jwt, process.env.JWT_SECRET);
db.query('SELECT * FROM userlists WHERE id = ?', [decoded.id], (err, results) => {
if(!results) {
return next();
}
req.lists = Object.values(JSON.parse(JSON.stringify(results)));
return next();
});
} catch (error) {
console.log(error);
return next();
}
} else {
next();
}
}
When I try to read this object I want to print the List name and then print each item in the string array on a seperate line as follows:
<div class="container">
<div class="title">
<h1>View a List</h1>
</div>
{{#each lists}}
<div>
<h3>{{listName}}</h3>
{{#each listItems}}
{{this}}
{{/each}}
</div>
{{/each}}
</div>
I have tried converting ‘listItems’ into a JSON object with JSON.parse(JSON.stringify(listItems)) but it returns a parser error: Expecting ‘ID’, got ‘INVALID’.
I’ve also tried just to parse it but it returs the same.
I am relatively new to most of this, especially handlebars so any help will be greatly appreciated.