How do i save an array with DataURL strings to local storage with Javascript?

Issue

This Content is from Stack Overflow. Question asked by Olivier Winder

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 string of DataURL’s. Getting the DataURL(s), pushing them to a string, and adding this string to the ‘recipe’ object. Is working.
If i ‘console.log(recipe.allImages)’ it returns the string with DataURL’s.
But this string 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)
    



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?