0

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.

9
  • 3
    you need to return something from a function if you want it to return something Commented Jul 4, 2021 at 12:25
  • @JaromandaX Actually I tried returning but the outcome was the same so I was just trying without the return and other ways. Commented Jul 4, 2021 at 12:32
  • It depends on where are you executing this this.todos = this.retrieve()? My be inside an regular function instead of arrow function. Commented Jul 4, 2021 at 12:38
  • @RajdeepDebnath retrieve() is a class method. this.todos is in the constructor of the class. Commented Jul 4, 2021 at 12:41
  • 1
    retrieve() shouldn't be in the constructor, you want it as a method of the class Commented Jul 4, 2021 at 12:59

1 Answer 1

2

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());

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.