Rahul Desai
Rahul Desai

Reputation: 15491

Unable to push item into array in localStorage

I am having a localStorage where I am keeping a list of movies that the user has bought tickets for. I created an array for this purpose. The problem in that I am unable to push new values to this array in localStorage.

Code:

if(window.localStorage){
    if(localStorage.getItem('movies_list')){
        var movies_list = localStorage.getItem('movies_list');
        console.log("Movies List: " + localStorage.getItem('movies_list'));
        var movie = $("#movie_name").val();
        movies_list.push(movie);  // Error here
        localStorage.setItem('movies_list',movies_list);
    }
    else{
        var movies_list = new Array();
        var movie = $("#movie_name").val();
        movies_list.push(movie);
        localStorage.setItem('movies_list',movies_list);
    }
}

Error:

Uncaught TypeError: Object Movie 1 has no method 'push'

The console.log() is always returning LIST: Movie 1, seems like the next movie is not getting pushed into the array.

How do I push the new values to the array?

jsFiddle

Upvotes: 2

Views: 2071

Answers (2)

Navin
Navin

Reputation: 604

localStorage accpets and stores only strings, you can't directly save an array. Instead you can do JSON.stringify during saving and JSON.parse during retrieving.

var movies = ["movie1","movie2","movie3"];
//Saving
localStorage.movies_list = JSON.stringify(movies);
//Retrieving
var list = JSON.parse(localStorage.movies_list);
list.push("movie4");

Upvotes: 2

sroes
sroes

Reputation: 15053

The items you add/get from the localStorage are strings. So you need to JSON encode / decode them.

localStorage.setItem('movies_list', JSON.stringify(movies_list));

And

var movies_list = JSON.parse(localStorage.getItem('movies_list'));

http://jsfiddle.net/Kx9R6/1/

Upvotes: 2

Related Questions