I am working with ReactJS and need to create an array to insert data, store it in localStorage, and view it later. I first create the array using this.subscriptionsList = [];
I then use this method to retrieve the data.
fetchNow = async (token, nextToken) => {
fetch("somewebsite")
.then(( unformattedData ) => {
return unformattedData.json();
})
.then(( webData) => {
for(let i = 0; i < webData.length; i++){
this.subscriptionsList.push("someData");
}
if(webData.hasOwnProperty('token')){
this.fetchNow(token, webData.token);
}else{
return;
}
})
}
The function is not complete as it is not the focal point of my question. It works fine and pushes the correct data.
I retrieve the data using this method:
this.fetchNow(response.accessToken, "")
.then( () => {
console.log(this.subscriptionsList);
console.log(JSON.stringify(this.subscriptionsList));
localStorage.setItem("subscriptionsList", JSON.stringify(this.subscriptionsList));
//console.log(JSON.parse(localStorage.getItem("subscriptionsList")));
})
The problem appears when I try to use JSON.stringify
. Doing console.log(this.subscriptionsList)
prints an array object with all the data inside of it as expected. However when I go to do console.log(JSON.stringify(this.subscriptionsList))
it returns []
. Further, when printing the object itself, the property length: 125
but when doing console.log(this.subscriptionsList.length)
it returns 0
and when accessing using this.subscriptionsList[0]
it returns undefined
. I was reading the specifications and it appears as though JSON.stringify should work with a javascript array. Am I missing something react specific or is this just not available with JSON.parse?
https://gyazo.com/72aafe248ef61649a38c06d03fb3d830
https://gyazo.com/c2690b4392774fe4a98254a4d15f3a32
https://gyazo.com/e0793b5ec05da4259e16100f275da414