Gago
Gago

Reputation: 97

Javascript (localstorage) only one value gets stored. How can I store everything?

I'm getting user data from an open API, I store it the localstorage, I can display all the data but only the first value is getting saved in the localstorage. How can I store all the data?

My code :

String.prototype.capitalize = function() {
  return this.charAt(0).toUpperCase() + this.slice(1);
}

function createNode(element) {
  return document.createElement(element);
}

function append(parent, element ) {
  return parent.appendChild(element);
}

const ul = document.getElementById('authors');
const url = 'https://randomuser.me/api/?results=10';

fetch(url)
  .then((resp) => resp.json())
  .then(function(data) {

    let authors = data.results;

    return authors.map(function(author) {

      const myObj = {
        name: `${author.name.first}`,
        lastname : `${author.name.last}`,
        email : `${author.email}`,
        location : `${author.location.city}, ${author.location.street}`,
        phone : `${author.phone}`
      }

      let li = createNode('li'),
          img = createNode('img'),
          span = createNode('span');

      let myObj_serialized = JSON.stringify(myObj);

      localStorage.setItem("myObj" , myObj_serialized);

      let myObj_deserialized = JSON.parse(localStorage.getItem("myObj"));

      document.getElementById('authors').innerHTML += 
        myObj_deserialized.name.capitalize() +  " " + 
        myObj_deserialized.lastname.capitalize() + " --- " + 
        myObj_deserialized.email + " --- " + 
        myObj_deserialized.location.capitalize() + " --- " + 
        myObj_deserialized.phone + "<br/> " ;

      console.log(myObj);    
    })
  })

  .catch(function(error) {
     console.log(error);
   });

results :

enter image description here

And here we see only 1 value gets stored instead of 10.

enter image description here

Upvotes: 3

Views: 3755

Answers (4)

Rajkumar
Rajkumar

Reputation: 1077

** Basic concept map() Methods:**

  1. map() creates a new array with the results of calling a function for every array element.
  2. This method calls provided function once for each element in an array in order.
  3. Array elements without values does not execute.
  4. Original array not change.

return authors.map(function(author,index, arr) {

      const myObj = {
        name: `${author.name.first}`,
        lastname : `${author.name.last}`,
        email : `${author.email}`,
        location : `${author.location.city}, ${author.location.street}`,
        phone : `${author.phone}`
      }

      let li = createNode('li'),
          img = createNode('img'),
          span = createNode('span');

          let myObj_serialized = JSON.stringify(myObj);

          localStorage.setItem(index , myObj_serialized);

          let myObj_deserialized = JSON.parse(localStorage.getItem(index));

          document.getElementById('authors').innerHTML += myObj_deserialized.name.capitalize() +  " " + myObj_deserialized.lastname.capitalize() + " --- " + myObj_deserialized.email + " --- " + myObj_deserialized.location.capitalize() + " --- " + myObj_deserialized.phone + "<br/> " ;

     

    })

OR

let myObj_serialized = JSON.stringify(myObj);

          localStorage.setItem(myObj.phone , myObj_serialized);

          let myObj_deserialized = JSON.parse(localStorage.getItem(myObj.phone));

OR

  let myObj_serialized = JSON.stringify(myObj);

          localStorage.setItem(myObj.email , myObj_serialized);

          let myObj_deserialized = JSON.parse(localStorage.getItem(myObj.email));

Upvotes: 1

NielsNet
NielsNet

Reputation: 828

Localstorage is a Map. So by calling setItem(key, value) you override the value. You can either use multiple keys or create an array and save the whole array.

Upvotes: 1

Vladimir Bogomolov
Vladimir Bogomolov

Reputation: 1794

You're overriding the same object every time in localstorage, so at the end of your map the localstorage item myObj is set to the last item from the authors array. I would suggest using something unique, like the user's email, and set that in the localstorage.

  localStorage.setItem(author.email , myObj_serialized);

  let myObj_deserialized = JSON.parse(localStorage.getItem(author.email));

Upvotes: 6

Bruno Paulino
Bruno Paulino

Reputation: 5810

As you are storing the data inside your map function, you are overwriting the object key myObj for every loop iteration.

you can notice that only the last object is in the LocalStorage.

You should store the entire response payload instead

const ul = document.getElementById('authors');
const url = 'https://randomuser.me/api/?results=10';
fetch(url)
  .then((resp) => resp.json())
  .then(function(data) {
    let authors = data.results;

    let myObj_serialized = JSON.stringify(authors);

    localStorage.setItem("myObj", myObj_serialized);

    // ... Everything else here
    // Now you should adapt your code.
  })
  .catch(function(error) {
    console.log(error);
  });

Upvotes: 4

Related Questions