Uncaught TypeError: Cannot read property 'forEach' of null

Uncaught TypeError: Cannot read property 'forEach' of null
0

#1

Hi, I have a error. What is the meaning of my array ? I add task but I have error. Also, I see the localstorage variable. I was thinking, if I did not used to local server, i met this problem.

Everything is okey but the only belowing code block has a problem

const tasks = JSON.parse(localStorage.getItem('tasks'));

tasks.forEach(function(task){
	console.log(task);
});

Full of code

document.querySelector('form').addEventListener('submit', function(e){
		const task = document.getElementById('task').value;

		let tasks;

		if(localStorage.getItem('tasks') === null){
			tasks = [];
		} else {
			tasks = JSON.parse(localStorage.getItem('tasks'));
		}

		tasks.push(task);

		localStorage.setItem('tasks', JSON.stringify(tasks));
		alert('Task saved');

		//console.log(task);
		e.preventDefault();

});

const tasks = JSON.parse(localStorage.getItem('tasks'));

tasks.forEach(function(task){
	console.log(task);
});

#2

stick a console.log(tasks) just after you load that from localStorage, see what the console shows you. The error you have, cannot read property forEach of null is telling you that tasks is, in fact, unassigned (or assigned a null value).


#3

When you first load the page there may not be a tasks variable in local storage. Where in your code do you actually set localStorage? If the only place you set localStorage is in the event listener callback function you show above, then until the form is submitted, there will be no tasks array to iterate over.