Search code examples
javascripthtmlnode.jsexpressexpress-handlebars

button should delete specific item on server side


I'm working on an app to track my expenses with javascript, nodejs , express and as templating engine handelbars.

So I have a div "list" which contains all expenses. ( i have an add button next to the div list, not visible on the pic)

Everytime a I add an expense , I add the div "obj" with a delete button ,a "B" button and some information about the expense.

here is the code in my html:

<div class="list">

{{#each expArr}}
    <div id="obj" class="obj">
     <form action="/removetodo" method="POST" >
     <button class="btn2">X</button> 
    </form>

    <button onclick="openNav()" class="btn">B</button>
    <a>{{date}}</a> <n>{{name}}</n> <a>{{value}} </a>
    {{description}}  
    </div>
{{/each}}

Now, my backend is runnning on a NodeJS server with express.

here is my index.js file :

var express = require('express');
var router = express.Router();


var expArr = [];


router.get('/', function(req, res, next) {
  res.render('index' , {expArr: expArr} );
});

 router.post('/addtodo', function (req, res, next) {



 var exp = new Object();

 exp.name = req.body.name;
 exp.value = req.body.val;
 exp.date = req.body.date;
 exp.description = req.body.descr;




 expArr.push(exp);
 res.redirect('/');

  });
 router.post('/removetodo', function (req, res, next) {


 expArr.pop();

 res.redirect("/");

 });


  module.exports = router;  

In addtodo I simply adding all the informtion to an array on the server (later I will add a database).

Now my question:

The delete button on every expense should delete the right expense. In other words, I want ,by clicking the delete button , that the right entry in the array on the server deletes.

How do I do that?

Thanks!


Solution

  • you're storing everything in memory, taking that for granted, you can start by using a plain object rather then an array to store your data

    expArr = {}
    

    and then add a unique identifier like a hash or a date in ms for each instance

    var exp = new Object();
    exp.id = new Date().getUTCMilliseconds();
    exp.name = req.body.name;
    exp.value = req.body.val;
    exp.date = req.body.date;
    exp.description = req.body.descr;
    
    expArr[exp.id] = exp;
    

    now be sure to pass from the client the right id when you want to remove an expense

    router.post('/removetodo', function (req, res, next) {
     if(expArr[req.body.id]) {
       delete expArr[req.body.id];
     }
     res.redirect("/");
    });