1

I get this error when im trying to display my json data in html it says undefined. i thinks it's because it cant find my goods.varer and goods.pris and goods.billede. How can i solve it. Please help, its for an exam project.

this is my code

varer.js

document.getElementById("clickMe").addEventListener('click', async() => {
  let table = document.getElementById('varerTable');
  
  let result = await fetch("http://localhost:8200/varer/getproducts", {method: 'GET', headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
})
  .then(res => res.json())
  .catch(console.log("error"));

  let tableHtml = `<tr>
  <th>varer</th>
  <th>pris</th>
  <th>billede</th>
  </tr>
  `;
  for(const goods in result){
    tableHtml += `
    <tr>
    <td>${goods.varer}</td>
    <td>${goods.pris}</td>
    <td><img src="${goods.billede}" style="height:50px;width:50px;"</td>
    </tr>
    `;

  }
  table.innerHTML = tableHtml;
});

varer-controller.js

router.delete("/delete:id", (req, res) => {
res.status(200).send(true);

});

router.get("/getproducts", (req, res) =>{
    res.status(200).json(products)
    console.log(products)
   })


//vis varer for en kategori
router.get("/getproductsforenkategori/:varer", (req, res)=>{
let category = req.params.varer;

if(products[category]){
  
  res.status(200).json({[category]:products[category]});
}
else{
  res.sendStatus(404)
}
});

varer.json

[{"varer":"ss","pris":"sss","billede":""},{"varer":"ss","pris":"sss","billede":""}]

varer-controller.js

router.post("/delete", (req, res) => {
    const varer = new varerModel(req.body.varer, req.body.pris, req.body.billede);
    vb.deleteGoods(varer);
    res.status(200).send(true);
  });

router.get("/getproducts", (req, res) =>{
    res.status(200).json(products)
    console.log(products)
   })

Models

class Goods {
    constructor(varer, pris, billede) {
      this.varer = varer;
      this.pris = pris;
      this.billede = billede;
    }
  }
  module.exports = Goods;

dbvarer.js

class VB {
    constructor() {
      this.salg = this.openFile(VARER_FILE);
    }
    /* CORE */
    // Save file
    saveFile(fileName, contentString) {
      fs.writeFileSync(ABSOLUTE_PATH + fileName, contentString);
    }
  
    // Open file
    //ændrer filename til userfile
    openFile(fileName) {
      const file = fs.readFileSync(ABSOLUTE_PATH + fileName);
      return JSON.parse(file);
    }
  
    /* LOGIN DB */
    saveGoods(varer) {
      this.salg.push(varer);
      this.saveFile(VARER_FILE, JSON.stringify(this.salg));
    }
    deleteGoods(varerne) {
        this.salg = this.salg.filter((x) => x.varer != varerne.varer);
        this.saveFile(VARER_FILE, JSON.stringify(this.salg));
      }
    
     
}
 
2
  • dear in the for loop console.log(goods) to see what properties it has Commented Dec 5, 2021 at 11:57
  • it gives me error and then 0 and 1?? Commented Dec 5, 2021 at 12:04

2 Answers 2

1

Looks like you are mixing async await and .then .catch, I suggest you use only async await is more readable.

document.getElementById("clickMe").addEventListener('click', async () => {
  try {
    const table = document.getElementById('varerTable');
    const result = await fetch("http://localhost:8200/varer/getproducts", {
      method: 'GET', 
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
    })
    const json = await result.json()
    let tableHtml = `<tr>
    <th>varer</th>
    <th>pris</th>
    <th>billede</th>
    </tr>
    `;
    for (const goods of json){
      tableHtml += `
      <tr>
      <td>${goods.varer}</td>
      <td>${goods.pris}</td>
      <td><img src="${goods.billede}" style="height:50px;width:50px;"</td>
      </tr>
      `;
    }
    table.innerHTML = tableHtml;

  } catch(err) {
    console.log('Oh no 😨')
    console.error(err)
  }
});

EDIT

Some refactor:

async function getGoods() {
  const response = await fetch("http://localhost:8200/varer/getproducts")
  const result = await response.json()
  return result
}

async function deleteGoods(id) {
  const response = await fetch("http://localhost:8200/varer/getproducts/" + id, { 
    method: 'DELETE'
  })
  const result = await response.json()
  return result
}

function renderTable(goods) {
    const table = document.getElementById('varerTable');
    let tableHtml = `
      <tr>
        <th>varer</th>
        <th>pris</th>
        <th>billede</th>
      </tr>`;
    for (const row of goods){
      tableHtml += `
        <tr>
          <td>${row.varer}</td>
          <td>${row.pris}</td>
          <td><img src="${row.billede}" style="height:50px;width:50px;"</td>
          <td><button onclick="handleDelete(${row.id})"> Delete </button></td>
          <td><button onclick="toDo"> Edit </button></td>
        </tr>
      `;
    }
    table.innerHTML = tableHtml;
}

async function handleDelete(id) {
  try {
    await deleteGoods(id)
    const goods = await getGoods()
    renderTable(goods)
  } catch(err) {
    console.error(err)
  }  
}

async function handleLoad() {
  try {
    const goods = await getGoods()
    renderTable(goods)
  } catch(err) {
    console.error(err)
  }  
} 

document.getElementById("clickMe").addEventListener('click', handleLoad);



Sign up to request clarification or add additional context in comments.

12 Comments

if i want to have a delete button beside each item, how should it be then. It could be so helpfull!!:)
You should add an id to each row <tr id="${row.id}">... and pass this id as param of the onclick="handleDelete(${row.id})" listner, then you can findElementById and delete it
Probably you want to send a DELETE request in handleDelete, if so... you can just call getGoods and renderTable after that
Can you accept my answer? 👉👈
Thank you so much for the answer, i'm struggling a bit to get it implemented, could you maybe show how to implement it. Could help me so much with this exam! and again thank you!
|
0

If your result is an array, then you shoud use for...of loop, like this:

 for(const goods of result){...}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.