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>
taskObjectdefined?