jensderyckere
jensderyckere

Reputation: 51

how to save api data into a localstorage?

I'm getting data from an API but i can't save my data into a localStorage.

I've already tried a couple of things but i can't seem to find the problem.

giveUsers();

function giveUsers() {

  for (let i = 0; i < 10; i++) {
  fetch('https://randomuser.me/api/')
    .then(function (response) {
      return response.json();
  })

  .then(function (data) {
    showUsers(data.results);
  })

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

  let showUsers = (users) => {
      users.forEach(user => {
        // console.log(user.registered.age);
        // console.log(user.location.city);
        let firstName = user.name.first;
        let id = user.id;

        console.log(firstName);
        localStorage.setItem('allUsers', firstName);  
     });
  };}
}


if(localStorage.getItem('allUsers')){
  console.log(localStorage.getItem('allUsers'));
}

I want my data into the localStorage.

Upvotes: 2

Views: 6654

Answers (3)

DaniFlex
DaniFlex

Reputation: 51

In your code it looks like you are setting localstorage for each user, effectively overwriting the last user added due to the same "key value" You should put them in a list and store your array as JSON. Remeber to use "window.localstorage": It should look something like this

window.localStorage.setItem('allusers', JSON.stringify(listOfUsers));  

Upvotes: 0

Aras
Aras

Reputation: 1597

if I understand your question correctly.

you can use async and await for your fetch. when you fetch data this needs a little time to get a response from a server because of that every time you set something null in your local storage.

you can find information about async/await here.

and about local storage visit here

Upvotes: 3

Pushprajsinh Chudasama
Pushprajsinh Chudasama

Reputation: 7949

You need to store your data as a string in localStorage

so use JSON.stringify();

let showUsers = (users) => {
  users.forEach(user => {       

    localStorage.setItem('user', JSON.stringify(user));  

  });
};

Upvotes: 3

Related Questions