Unable to store the state of an array inside map - Reactjs - javascript

I am working on reactjs project where i have to store the array value in a local variable that i am parsing form a JSON data . I am successfully able to parse the data using map function , i want to store the result data in a global array , but i am unable to declare state inside map function, how do can i get access to the array which i am retrieving through map. below is my code.
//post data input
let postData = { Userid: this.props.Userid };
//post data is a method which return's the json array its a post request
PostData('UserDetails', postData).then((result) => {
//storing the data in a variable
responseJson = result;
{
//parsing the json using map
responseJson.Jiralist.map((rowdata, i) => (
// i want to store this value in a global array
console.log("", rowdata.jirakey);
))
}

The map() method creates a new array with the results of calling a provided function on every element in the calling array.
If dont really need to modify the existing array, you can use forEach.
And create a global array and push the new item using spread operator
let globalArr = [];
responseJson.Jiralist.forEach((rowdata, i) => ([...globalArr, rowdata.jirakey]))

Related

vuejs make array of objects data

I have array of data (selected items) and I need to extract ids of this array into new array so I can send those ids only to back-end.
Code
method
toggleSelection(rows) {
console.log('this.multipleSelection : ',this.multipleSelection); // prints my default array (include all data)
this.multipleSelection.forEach(row => {
console.log('rows: ', row) // get each object of array (extract ids here)
// send axios request to backend (ids only)
});
},
Screenshot
here is result of console codes above
any idea?
At first I need to say I never worked with Vue.js. But in simple vanilla-javascript you could use the map function. I don't know if this works but Here is a possible answer:
yourids = this.multipleSelection.map(row => row.id);

Store JSON to localstorage not working

After pushing a button I would like to save an item (nested JSON) into a new Array and store it to the localstorage.
addFavourite(card) {
console.log(JSON.stringify(card));
var cards = [];
this.cardfavouriteArray.push.apply(cards, card)
this.storage.set('favouriteData', this.cardfavouriteArray);
}
getData() {
var data = this.storage.get('favouriteData');
if(data){
this.storage.get('favouriteData').then((val) => {
console.log('test', JSON.stringify(val));
});
}
I get no error, but 'test' is always empty. I need it as an array.
Set and Get method for localstorage varies on which service you are using
1.HTML5 localStorage- If you are using HTML5 localStorage directly then you should use localStorage.getItem
and localStorage.setItem
2.localstorage is limited to store only string key/value pairs.Use JSON.stringify and JSON.parse when using setting and getting from localstorage
addFavourite(card) {
console.log(JSON.stringify(card));
var cards = [];
this.cardfavouriteArray.push.apply(cards, card)
this.storage.setItem('favouriteData', JSON.stringify(this.cardfavouriteArray));
}
getData() {
var data = this.storage.get('favouriteData');
if(data){
this.storage.getItem('favouriteData').then((val) => {
console.log('test', JSON.parse(val));
});
}
3.ng2-webstorage- In case of ng2-webstorage this.storage.retrieve and this.storage.store will work.
Change this.storage.set('favouriteData', this.cardfavouriteArray); to localStorage.set('favouriteData', JSON.stringify(this.cardfavouriteArray)); (It's a pre-defined method by angular). Also stringify the array.
Set array in local storage like this:
localStorage.setItem('favouriteData', JSON.stringify(this.cardfavouriteArray));
Get array from local storage like this:
var data = JSON.parse(localStorage.getItem('favouriteData'));
Explanation: It is because localstorage can not store object, it stores in string format. So we need to JSON.stringify the object. Also localStorage has function name setItem and getItem as defined here: http://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage. When we get the string from localstorage, we need to JSON.parse to convert it back to object.
You are using this.storage.set and this.storage.get. It is not clear which library are you using, but the code I mentioned will work in Angular or any framework. Since localStorage.setItem and localStorage.getItem is pure javascript.

React Native Getting specific child values from JSON tree with Firebase

So I am using React Native and firebase and I have a JSON tree in firebase that is structured like this
{"Message"
{"-LCi0UViBvOn4eh9cqzW":
{"contents":"hello",
"timestamp":1526559275118}
}
}
I am trying to retrieve the contents of the message and store it in an object, and for now just read that value to the console. Here is my code where I attempt this:
const firebaseApp = firebase.initializeApp(firebaseConfig);
let db = firebaseApp.database();
let ref = db.ref("/message");
Attempting the read:
componentDidMount() {
ref.on("value", function(snapshot) {
var messageText = JSON.stringify(snapshot.val());
console.log(messageText);
var parsedMessage = JSON.parse(messageText);
console.log(parsedMessage.contents);
});
}
The first console.log gives me the following results:
{"-LCi0UViBvOn4eh9cqzW":{"contents":"hello","timestamp":1526559275118}}
But the next one console.log where I try to read the specific data from the parsed object always outputs undefined.
What am I doing wrong that won't allow me to retrieve that specific data from my JSON tree?
When you do your second JSON.parse and then console.log the parsedMessage.contents, that is actually nested within the key "-LCi0UViBvOn4eh9cqzW" so you should do console.log(parsedMessage["-LCi0UViBvOn4eh9cqzW"].contents) as the contents key is within the value of the root element.

How to query Firebase data after using .push() to add data?

Here is the code for when I'm pushing the data to Firebase:
firebase.database().ref(`booklogs/${uid}/${book_id}`).push(page_id)
booklogs :
{HUMjSHxVKAPfVXzOId9zCBkGOgv1:{
book28917: {
-KYp4FdYYODDZG1FX-Pb: 1
}
}
}
My problem is when I query the data, the child node of the ${book_id} includes the push key, but I only want to get the value which is 1 and not the push key.
The code I use to query is:
var booklogs = db.ref(`booklogs/${uid}/${project}`);
booklogs.once('value')
.then((snapshot) => {
console.log(`pages viewed are ${snapshot.key}: ${snapshot.val()}`);
console.dir(snapshot.val());
}).catch((error) => {
console.log(`Error : ${error}`);
});
The data returned in the console is:
pages viewed are 2634651: [object Object]
{ '-KYp4FdYYODDZG1FX-Pb': 1 }
Any input would be much appreciated. Thanks!
If you only want the '1' and not the push key, try using .set()
firebase.database().ref(`booklogs/${uid}/${book_id}`).set(page_id)
That will get rid of the object and just give you the value that you wanted. Push automatically generates a key for every value you add, so you will always get an object back. From the Firebase docs - "For basic write operations, you can use set() to save data to a specified reference, replacing any existing data at that path."
https://firebase.google.com/docs/database/web/read-and-write

How to get firebase id

Anyone know how to get the Firebase unique id? I've tried name(), name, key, key(). Nothing works.
I am able to see the data but I have no idea how to get the id back. I need it.
//Create new customers into firebase
function saveCustomer(email) {
firebase.database().ref('/customers').push({
email: email
});
firebase.database().ref('/customers').on("value", function(snapshot) {
console.log(snapshot.val());
console.log(snapshot.value.name());
}, function(errorObject) {
console.log("The read failed: " + errorObject.code);
});
}
The call to push will return a Firebase reference. If you are using the Firebase 3 API, you can obtain the unique key of the pushed data from the reference's key property:
var pushedRef = firebase.database().ref('/customers').push({ email: email });
console.log(pushedRef.key);
The key for the pushed data is generated on the client - using a timestamp and random data - and is available immediately.
Calling push() will return a reference to the new data path, which you can use to get the value of its ID or set data to it.
The following code will result in the same data as the above example, but now we'll have access to the unique push ID that was generated:
// Generate a reference to a new location and add some data using push()
var newPostRef = postsRef.push();
// Get the unique ID generated by push()
var postID = newPostRef.key();
Documentation.
but this method won't work when you also need the id beforehand
for example to save it in the database itself.
Firebase suggests this:
// Add a new document with a generated id.
var newCityRef = db.collection("cities").doc();
--for some reason, push() and key() didn't work for me. also in this case the reference contains the whole path. so need a different method for getting the id.
Doing this below helped to get the id from the reference and use it.
const ref = db.collection('projects').doc()
console.log(ref.id) // prints the unique id
ref.set({id: ref.id}) // sets the contents of the doc using the id
.then(() => { // fetch the doc again and show its data
ref.get().then(doc => {
console.log(doc.data()) // prints {id: "the unique id"}
})
})

Categories

Resources