Reputation: 415
I need to store a JSON in a variable. I have the next function:
retrieve(){
JSON.parse(localStorage.getItem('todos'));
}
And i'm trying to store the return of the function in the variable.
this.todos = this.retrieve()
But I'm getting:
model.js:5 Uncaught TypeError: Cannot read property 'retrieve' of undefined
If i do this instead, it works:
this.todos = JSON.parse(localStorage.getItem('todos'));
Why is that happening?
Edit: Full code
export default class Model {
constructor(){
this.view = null;
this.todos = this.retrieve();
if(!this.todos || this.todos.length < 1){
this.todos = [
{
id: 0,
title: 'default',
description: 'default',
completed: false,
}
]
this.id = 1;
}
this.id = this.todos[this.todos.length - 1].id + 1;
retrieve(){
return JSON.parse(localStorage.getItem('todos'));
}
}
Thanks everyone.
Upvotes: 0
Views: 91
Reputation: 3920
Your class level methods should be outside the constructor.
localStorage.setItem('todos', JSON.stringify([{id:1},{id:2},{id:3}]))
class Model {
constructor(){
this.view = null;
this.todos = this.retrieve();
if(!this.todos || this.todos.length < 1){
this.todos = [
{
id: 0,
title: 'default',
description: 'default',
completed: false,
}
]
this.id = 1;
}
this.id = this.todos[this.todos.length - 1].id + 1;
}
retrieve(){
return JSON.parse(localStorage.getItem('todos'));
}
}
console.log(new Model());
Upvotes: 2