manthankumbhar
manthankumbhar

Reputation: 15

Can't understand the error with JSON.parse

I'm working on a todoList and I'm understanding the process of localstorage, so i tried adding default items in my todoList

var bla = "[{text: 't1', key: 1602048390632}, {text: 't2', key: 1602048392604}, {text: 't3', key: 1602048393953}]"; 
   
   this.state = { 
    items:  JSON.parse(bla)
   };

But here It shows a cross origin that react doesn't have access to show. The output I need is t1, t2, t3. The CORS error

 ReactDOM.render(
   <div>
    <TodoList/>
      </div>,

Upvotes: 0

Views: 98

Answers (1)

Derek Wang
Derek Wang

Reputation: 10193

You cannot use JSON.parse for bal variable because the key is not covered with double quotes("").

In this case, you can use eval() function.

var bla = "[{text: 't1', key: 1602048390632}, {text: 't2', key: 1602048392604}, {text: 't3', key: 1602048393953}]"; 
   
const state = { 
  items: eval(bla)
};
console.log(state);

Upvotes: 2

Related Questions