Skip to content

Instantly share code, notes, and snippets.

@mirsahib
Last active July 27, 2019 06:14
Show Gist options
  • Select an option

  • Save mirsahib/c24a0c02eb03619f51100659213c84c8 to your computer and use it in GitHub Desktop.

Select an option

Save mirsahib/c24a0c02eb03619f51100659213c84c8 to your computer and use it in GitHub Desktop.
$(document).ready(function() {
loadApiData(function showApiData() {
//display the localstorage data
nowPlaying = JSON.parse(localStorage.getItem("now_playing"));
upComming = JSON.parse(localStorage.getItem("upcomming"));
popular = JSON.parse(localStorage.getItem("popular"));
console.log(nowPlaying);
console.log(upComming);
console.log(popular);
});
});
function loadApiData(callback) {
//if local storage is empty fetch
if (localStorage.length != 3) {
//if localstorage is empty fetch data
//api url (api key will be provide upon request)
const url1 =
"https://api.themoviedb.org/3/movie/now_playing?api_key=<apikey>&language=en-US&page=1";
const url2 =
"https://api.themoviedb.org/3/movie/upcoming?api_key=<apikey>&language=en-US&page=1";
const url3 =
"https://api.themoviedb.org/3/movie/popular?api_key=<apikey>f&language=en-US&page=1";
//data will be stored in different table with different key
var fileName = ["now_playing", "upcomming", "popular"];
let nowPlaying = fetch(url1);
let upComming = fetch(url2);
let popular = fetch(url3);
Promise.all([nowPlaying, upComming, popular])
.then(files => {
var i = 0;
files.forEach(file => {
process(file.json(), fileName[i]);
i++;
});
callback();//where should i put this callback to display the data synchronously
})
.catch(err => {
console.log(err);
});
} else {
callback();//if localstorage is not empty go to display function
}
}
//store the data in local storage
let process = (prom, fileName) => {
prom.then(data => {
var items = [];
for (var i = 0; i < 5; i++) { // i only need only 5 item
items.push(data["results"][i]);
}
localStorage.setItem(fileName, JSON.stringify(items));
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment