0

I'm having an issue coding a dynamic list in JavaScript. I basically have a simple two-layer system that will dynamically generate each list item and pair it with a object which will then be returned to the list with some basic properties. In short each list item is built as follows:

The Skeleton An object that contains reusable properties and functions that will be common between items. In the future I plan on this containing a large amount of data I do not want to keep on my server to have to send to each user every time they view the component.

export default {
  name: 'Default',
  chapters: []
}

The Meat Adds specific data to the skeleton which is then exported. Again, this is going to add a decent amount of data to the object that will be paired with the list item.

import Book from '@/book.js'

Book.name = 'The Almanac'
Book.chapters = ['Chapter 1', 'Chapter 2', ...]

export default Book

Populating The List The list is populated when the component mounts, retrieving information on what the user can access from the server.

  get (list) {
    DataService.getBooks(localStorage.getItem('Username')).then((res) => {
      res.data.forEach(function (item) {
        list.push({
          title: item,
          obj: import('@/TheAlmanac/book.js')
            .then(function (res) {
              return res.default
            })
        })
      })
    })
  }

The issue I'm having is that when I attempt to assign the result of the promise from the dynamic import statement to obj using the following line of code:

this.items = this.items[index].obj.chapters

Im getting:

Uncaught TypeError: Cannot read properties of undefined (reading 'obj')

I've also tried arrow functions but it returns the same.

Can someone please point out what I'm doing incorrectly or let me know if what I would like to do is possible / good JavaScript practice?

Kris
  • 37
  • 5

0 Answers0