I have a function addRecipe() which creates a recipe object and saves it to local storage every time the submit button is clicked.
I need to save images in this object as a an array of DataURL strings. Getting the DataURL(s), pushing them to an empty string, and adding this string to the 'recipe' object. Is working. If i 'console.log(recipe.allImages)' it returns the array with DataURL strings. But this array is empty inside of my LocalStorage. Why is it empty inside of my LocalStorage, and how do i fix this?
Simplified code :
const submitBtn = document.querySelector('.submit-btn'); let images = []; function addRecipe(){ let imageArr = document.querySelector('#recipe-images').files; // array of files for(let i = 0; i < imageArr.length; i++){ // loops through all files const reader = new FileReader(); reader.readAsDataURL(imageArr[i]) reader.addEventListener('load', function (e) { let image = e.target.result; images.push(image); }) } console.log(images) // returns the array with DataURL's let recipe = { allImages: images } console.log(recipe.allImages); // returns the array with DataURL's // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! localStorage.setItem('allRecipes', JSON.stringify(recipe)); // localstorage does not contain string of DataURL's but an empty string }; submitBtn.addEventListener('click', addRecipe)