3

I am working on a TODO list, I'm trying to make this work with local storage. But there is a problem in my code I can't resolve.

The function getTaskArray() retrieved the, whats meant to be, array from the local storage under the key 'tasks'. If it cannot find it it created a new array instead.

The pushData() function should push the task object into the array. But I get the following error: taskArray.push is not a function.

I've attached a snippet of my code below.

Thanks in advance for your help!

var taskArray;
function getTaskArray() {
    var taskArrayString = localStorage.getItem("tasks");
    if (taskArrayString !== null && typeof taskArrayString === "string") {
        taskArray = taskArrayString;
        console.log("Succesfully retrieved 'tasks' and contents.");
    } else {
        console.log("Succesfully retrieved 'tasks', contents were not a string or held no contents. Contents of 'tasks' reset to empty array");
        var emptyArray = JSON.stringify(new Array());
        localStorage.setItem("tasks", emptyArray);
        taskArray = localStorage.getItem("tasks");
    };
};

var taskString;

function pushData() {
    taskString = JSON.stringify(taskObject);
    taskArray = taskArray.push(taskString);
};

Update:

The complete version of my code:

// All functions
var taskFromHtml;
var priorityFromHtml;

function getTaskInput() {
    try {
        taskFromHtml = $("#taak").val();
        priorityFromHtml = $("#prioriteit").val();
        console.log("Succesfully retrieved data. Task: " + taskFromHtml + ". Priority: " + priorityFromHtml + ".");
    } catch(e) {
        console.log("Failed to retrieve data, unexpecter error.");
    };
};

var taskObject;
function taskToObject() {
    taskObject = {
        task: taskFromHtml,
        priority: priorityFromHtml,
        finished: false
    }; 
};

var taskArray;
function getTaskArray() {
    var taskArrayString = localStorage.getItem("tasks");
    if (taskArrayString !== null && typeof taskArrayString === "string") {
        taskArray = JSON.parse(taskArrayString); // <------
        console.log("Succesfully retrieved 'tasks' and contents.");
    } else {
        console.log("Succesfully retrieved 'tasks', contents were not a string or held no contents. Contents of 'tasks' reset to empty array");
        var emptyArray = JSON.stringify(new Array());
        localStorage.setItem("tasks", emptyArray);
        taskArray = localStorage.getItem("tasks");
        taskArray = JSON.parse(taskArray); // <------
    };
};

var taskString;

function pushData() {
    taskString = JSON.stringify(taskObject);
    taskArray = taskArray.push(taskString);
};

And it's HTML:

  <form id="todoInsert" action="#">
        <input type="text" name="task" id="taak">
        <select id="prioriteit">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
        </select>

        <input type="submit" id="formSubmit">
    </form>
    <div id="addItem">+</div>
4
  • Where's taskObject defined? Commented Nov 19, 2015 at 8:55
  • @BasvanStein it is a little further in the code, have not yet started debugging that. But there is a line of code in the snippet above: localStorage.setItem("tasks", []); Commented Nov 19, 2015 at 9:02
  • @DemiënDrost ok, be sure to do JSON.stringify when setting the localStorage as well, see my updated answer for your fixed code. Commented Nov 19, 2015 at 9:16
  • @hindmost var taskObject; function taskToObject() { taskObject = { task: taskFromHtml, priority: priorityFromHtml, finished: false }; }; Commented Nov 19, 2015 at 9:16

2 Answers 2

5

You get the error because you try to perform the push function on a String instead of an array.

When you get the String from the localStorage you need to parse it using JSON.parse().

taskArray = JSON.parse( localStorage.getItem("tasks"));

And also when your receive is succesfully in the if part:

taskArray = JSON.parse(taskArrayString);

Your complete working code would be:

var taskArray;
function getTaskArray() {
    var taskArrayString = localStorage.getItem("tasks");
    if (taskArrayString !== null && typeof taskArrayString === "string") {
        taskArray = JSON.parse(taskArrayString); // <------
        console.log("Succesfully retrieved 'tasks' and contents.");
    } else {
        console.log("Succesfully retrieved 'tasks', contents were not a string or held no contents. Contents of 'tasks' reset to empty array");
        var emptyArray = JSON.stringify(new Array());
        localStorage.setItem("tasks", emptyArray);
        taskArray = localStorage.getItem("tasks");
        taskArray = JSON.parse(taskArray); // <------
    };
};

var taskString;

function pushData() {
    taskString = JSON.stringify(taskObject);
    taskArray.push(taskString); // <----- !No need to assign there.
};

Here you can see a working JsFiddle: https://jsfiddle.net/txvp9uwc/2/

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

4 Comments

I understand what you mean. But when I test it, after pushData(), when I look for the contents of taskArray, it returns '1' (without the quotes). And taskArray[0] is not working either. When I look in my browser's localStorage it says it holds key: tasks, with value: [].
@DemiënDrost That might be related to your other code, I do not know what taskObject is for instance so I can not know how to fix that. Let me make a fiddle for you to show this part works.
@DemiënDrost, I found another bug in your code, when you perform push there is no need to assign the variable again. Just taskArray.push(taskString); is enough.
that might have been it. I enclosed my entire code. But I will test that as well. Your last suggestion fixed my problem! Great thanks you for your help.
2

You can only save the data in string format in the local storage. You can not save, dates, numbers or any other data types. For that you can serialize and deserialize your data as JSON string and then persist the data.

There are some awesome wrapper libraries available which do that for you: https://github.com/nbubna/store or https://github.com/marcuswestin/store.js/

Update

You need to deserialize your string after retrieval before using it:

var taskArrayString = localStorage.getItem("tasks");
if (taskArrayString !== null && typeof taskArrayString === "string") {
    taskArray = JSON.parse(taskArrayString);   // deserializing here
    console.log("Succesfully retrieved 'tasks' and contents.");
}

2 Comments

Well, as you can see, I have some JSON strings. But obviously there is somekind of problem somewhere. I'd rather fix that in JavaScipt then by adding another library
@DemiënDrost, do you deserialise from JSON when retrieveing the value from localstorage, as far as i can see, this is dot done, you get back a string, instead of array for example

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.