javascriptecmascript-6localforage

Javascript, localForage, passing array between object literals with getter


I've got the following object literals where I'm trying to pass a todoList array between a store object (using localForage) and a view object.

const store = {
  setUpStore() {
    this.todos = localforage.createInstance({
      name: 'myApp',
      storeName: 'todos'
    });
    this.completed = localforage.createInstance({
      name: 'myApp',
      storeName: 'completed'
    });
  },

// Code omitted for brevity

  get todoList() {
    const todoList = [];
    this.todos.iterate((value, key, iterationNumber) => {
      let item = {id: key, title: value.title};
      if (value.prioritized === true) {
        todoList.unshift(item);
      } else {
        todoList.push(item);
      }
    }).then(() => {
      console.log('Got todo list');
    }).catch((err) => {
      console.log(`There was an error: ${err}`);
    });
    return todoList;
  },
}

const view = {
  // Code omited for brevity

  displayTodos() {
    todoList = store.todoList;
    console.log(todoList); // This logs what appears to be an array
    todoList.forEach((item) => {
      // This doesn't work
      console.log(item.title);
    });
  }
}

When I call the store.todoList getter in the console, I get an array that I can work with. The console.log(todoList) in the view.displayTodos() method seems to work, but calling forEach() or doing any other kind of array operations on the todoList in the view method does not work. What's going on here?


Solution

  • the first method should be like this

    get todoList() {
        const todoList = [];
        return this.todos.iterate((value,id) =>{
            let item = { id, title: value.title};
            if (value.prioritized === true) {
                todoList.unshift(item);
            } else {
                todoList.push(item);
            }
        }).then(() => {
            console.log('Got todo list');
            return todoList
        }).catch((err) => {
            console.log(`There was an error: ${err}`);
        });
    },
    

    inside the 'then' i'm returning what i really want, the array, inside the Promise. The second method should be like this

    displayTodos() {
        store.todoList.then(arr=> arr.forEach((item) => {
            console.log(item.title);
        }))
    }    
    

    the result I'm using is a Promise, so i have to work inside the 'then' to see the array