Beginner question. I’m working on a project where I need to create a blog-type site with node/express/ejs. I’m stuck at the part where I need to display submitted posts and allow the user to view/edit/delete them. Here’s the part I’m stuck on:
<div class="post-tile">
<div class="post-info">
<img src="images/user1.svg" alt="user icon" width="30" />
<h2 class="post-title-ex"><%= posts[displayID].title %></h2>
<h3 class="post-author-ex"><%= posts[displayID].author %></h3>
</div>
<p class="post-content-ex"><%= posts[displayID].content %></p>
</div>
import express from 'express';
import bodyParser from 'body-parser';
const port = 3000;
const app = express();
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(port, () => {
console.log(`Listening on port ${port}`);
})
app.get('/', (req, res) => {
let data = {
posts: blogPosts,
displayID: 0,
};
res.render('index.ejs', data);
});
app.post('/submit', (req, res) => {
let uName = req.body['user'];
let title = req.body['title'];
let content = req.body['post-content'];
let postIDassign = blogPosts.length + 1;
blogPosts.push(new Post(uName, title, content, postIDassign));
res.redirect('/');
})
/* For blog posts */
const blogPosts = [];
function Post(user, title, content, postID) {
this.user = user;
this.title = title;
this.content = content;
this.postID = postID;
}
I’ve tried implementing a client-side javascript file to handle changing the posts based on an HTML dataset with this code:
const postSelection = document.querySelectorAll('.post-title');
const postDisplayTitle = document.querySelector('.post-title-ex');
const postDisplayAuthor = document.querySelector('.post-author-ex');
const postDisplayContent = document.querySelector('.post-content-ex');
const blogPosts = posts;
postSelection.forEach((post) => {
post.addEventListener('click', () => {
let ID = (post.dataset.postid) - 1;
console.log(ID);
displayID = ID;
})
})
My issue is that I can’t figure out a way to update the displayID once it’s already rendered on the page. This is my first time using backend languages on a full project and I know there’s something very basic I’m missing, the entire premise may need to be rethought, etc.