Trying to implement pagination using react but cannot seem to figure out a way to append the new response to an already existing state variable.
I'm trying to implement a load more functionality wherein the data is appended to the list itself.
const handleLoadMoreClick = () => {
let tempObj = postparem;
tempObj.pagenumber = tempObj.pagenumber + 1;
setPostparem(tempObj);
getProductChildMenu(APIProductList, postparem);
setCopyMenu(...copyMenu, productChildMenu);
};
Currently the map function is running iterating over productChildMenu so it replaces the data but i want to append the data in productChildMenu to copyMenu.
I tried iterating over productChildMenu and pushing each element to copyMenu but it is coming out undefined or if i push it completely at once, it creates a 2d array which does not iterate in map correctly.
You must do the following to merge 2 objects into your state.
const handleLoadMoreClick = () => {
...
...
setCopyMenu({...copyMenu, ...productChildMenu});
};
You cannot do what you are doing with tempObject here:
let tempObj = postparem;
// this is wrong.
tempObj.pagenumber = tempObj.pagenumber + 1;
setPostparem(tempObj);
Even though you call the variable tempObj a "temporary object", it is not a new object. It is just a reference to the object stored in the variable postparem.
So your code is identical to the (equally wrong) postparem.pagenumber = postparem.pagenumber + 1.
Instead, you really have to create a new object:
let tempObj = {
...postparem,
};
and then you can either modify that, or already introduce your change on object creation.
That would look like
let tempObj = {
...postparem,
pagenumber: postparem.pagenumber + 1,
};
setPostparem(tempObj);
Or even a bit shorter:
setPostparem({
...postparem,
pagenumber: postparem.pagenumber + 1,
});
I'm trying to achieve the following Array/Object,
[
1:[{data:data},{data:data}]
]
How would this be achieved?
I got thus far,
var data = [];
data['1'] = {data:data}
but this just overwrites.
The notation [] is for making Arrays, {} is for making Objects.
See the following
const data = {}; // Initialize the object
data['1'] = []// Makes data={'1':[]}
data['1'].push({data: 'data'}) // Makes data = {'1':[{data:'data'}]}
OR
const data = []; // Initialize the Array
data.push([]) // Makes data=[[]]
data[0].push({data: 'data'}) // Makes data = [[{data:'data'}]]
If i get you right you want to push objects into an array inside of an hashtable ( which can be easily implemented using an object in javascript).
So we need an object first:
const lotteries = {};
Now before storing data, we need to check if the relating array exists, if not we need to create it:
function addDataToLottery(lottery, data){
if(!lotteries[lottery]){ //if it doesnt exist
lotteries[lottery] = []; //create a new array
}
//As it exists definetly now, lets add the data
lotteries[lottery].push({data});
}
addDataLottery("1", { what:"ever"});
console.log(lotteries["1"]));
PS: If you want to write it in a fancy way:
class LotteryCollection extends Map {
constructor(){
super();
}
//A way to add an element to one lottery
add(lottery, data){
if(!this.has(lottery)) this.set(lottery, []);
this.get(lottery).push({data});
return this;
}
}
//Create a new instance
const lotteries = new LotteryCollection();
//Add data to it
lotteries
.add("1", {what:"ever"})
.add("1", {sth:"else"})
.add("something", {el:"se"});
console.log(lotteries.get("1"));
I'm trying to .map through data returned from an API (the NASA API). The issue I'm having is with deeply nested properties -- here's an example.
What's the best way to get the nested name and estimated_diameter properties data in React? All the data's being brought in just fine via axios. Logging out the state returns this:
I'm having trouble map'ing through the data because of the nested objects and arrays.
Assume the nasa data json is saved in the variable nasaData, the code below will print all the name and the estimated_diameter
var nearEarthObjects = nasaData['near_earth_objects'];
for (var property in nearEarthObjects) {
if (nearEarthObjects.hasOwnProperty(property)) {
var data = nearEarthObjects[property];
data.forEach(function(d){
console.log(d['name']);
console.log(d['estimated_diameter']);
});
}
}
ps: this might be for a reactjs project but it's really just javascript
You can map through the dates first.
const { near_earth_objects } = nasaData; //assuming nasaData is the json object
const dateKeys = Object.keys(near_earth_objects);
const nameAndEstimatedDiameters = dateKeys.map((dateKey) => {
const dateData = near_earth_objects[dateKey];
const { name, estimated_diameter } = dateData;
return { name, estimated_diameter };
});
//now nameAndEstimatedDiameters is an array of objects here
//which you can map again
I need to create a new object with a generated key and update some other locations, and it should be atomic. Is there some way to do a push with a multi-location update, or do I have to use the old transaction method? This applies for any client platform, but here's an example in JavaScript.
var newData = {};
newData['/users/' + uid + '/last_update'] = Firebase.ServerValue.TIMESTAMP;
newData['/notes/' + /* NEW KEY ??? */] = {
user: uid,
...
};
ref.update(newData);
There are two ways to invoke push in Firebase's JavaScript SDK.
using push(newObject). This will generate a new push id and write the data at the location with that id.
using push(). This will generate a new push id and return a reference to the location with that id. This is a pure client-side operation.
Knowing #2, you can easily get a new push id client-side with:
var newKey = ref.push().key(); // on newer versions ref.push().key;
You can then use this key in your multi-location update.
I'm posting this to save some of future readers' time.
Frank van Puffelen 's answer (many many thanks to this guy!) uses key(), but it should be key.
key() throws TypeError: ref.push(...).key is not a function.
Also note that key gives the last part of a path, so the actual ref that you get it from is irrelevant.
Here is a generic example:
var ref = firebase.database().ref('this/is/irrelevant')
var key1 = ref.push().key // L33TP4THabcabcabcabc
var key2 = ref.push().key // L33TP4THxyzxyzxyzxyz
var updates = {};
updates['path1/'+key1] = 'value1'
updates['path2/'+key2] = 'value2'
ref.update(updates);
that would create this:
{
'path1':
{
'L33TP4THabcabcabcabc': 'value1'
},
'path2':
{
'L33TP4THxyzxyzxyzxyz': 'value2'
}
}
I'm new to firebase, please correct me if I'm wrong.
How do you only pull only the nodes from firebase and not the keys using javascript? In other words, I only want the values of the key-value pairs from the below firebase, which means I don't want the unique keys below but just what's underneath.
Currently, my code is..
function PullFirebase() {
new Firebase('https://myfirebase.firebaseIO.com/quakes').on('value', function (snapshot) {
var S = snapshot.val();
function printData(data) {
var f = eval(data);
console.log(data + "(" + f.length + ") = " + JSON.stringify(f).replace("[", "[\n\t").replace(/}\,/g, "},\n\t").replace("]", "\n]"));
}
printData(S);
});
}
PullFirebase();
This produces the following in the console
[object Object](undefined) = {"-JStYZoJ7PWK1gM4n1M6":{"FID":"quake.2013p618454","agency":"WEL(GNS_Primary)","depth":"24.5703","latitude":"-41.5396","longitude":"174.1242","magnitude":"1.7345","magnitudetype":"M","origin_geom":"POINT (174.12425 -41.539614)","origintime":"2013-08-17T19:52:50.074","phases":"17","publicid":"2013p618454","status":"automatic","type":"","updatetime":"2013-08-17T19:54:11.27"},
"-JStYZsd6j4Cm6GZtrrD":{"FID":"quake.2013p618440","agency":"WEL(GNS_Primary)","depth":"26.3281","latitude":"-38.8725","longitude":"175.9561","magnitude":"2.6901","magnitudetype":"M","origin_geom":"POINT (175.95611 -38.872468)","origintime":"2013-08-17T19:45:25.076","phases":"13","publicid":"2013p618440","status":"automatic","type":"","updatetime":"2013-08-17T19:48:15.374"},...
but I'd like to only have the dictionaries , such as
[{"FID":"quake.2013p618454","agency":"WEL(GNS_Primary)","depth":"24.5703","latitude":"-41.5396","longitude":"174.1242","magnitude":"1.7345","magnitudetype":"M","origin_geom":"POINT (174.12425 -41.539614)","origintime":"2013-08-17T19:52:50.074","phases":"17","publicid":"2013p618454","status":"automatic","type":"","updatetime":"2013-08-17T19:54:11.27"},{"FID":"quake.2013p597338","agency":"WEL(GNS_Primary)","depth":"5.0586","latitude":"-37.8523","longitude":"176.8801","magnitude":"2.2362","magnitudetype":"M","origin_geom":"POINT (176.88006 -37.852307)","origintime":"2013-08-10T00:21:54.989","phases":"17","publicid":"2013p597338","status":"automatic","type":"","updatetime":"2013-08-10T03:42:41.324"}...]
If I understand you correctly, you want to get all child objects under quakes.
You generally have two approach here:
Get the value of the parent node and loop over the children
Monitor as children are added/updated/removed to the parent node
Your approach matches with #1, so I'll answer that one first. I'll also give an example of approach #2, which is more efficient when your data set changes.
Iterate children of a Firebase ref
In your on('value', handler you can skip the unique IDs using forEach:
new Firebase('https://myfirebase.firebaseIO.com/quakes').on('value', function (snapshot) {
var quakes = [];
snapshot.forEach(function(childSnapshot) {
quakes.push(childSnapshot.val());
});
var filter = new crossfilter(quakes);
});
The forEach function is sychronous, so we can simply wait for the loop to finish and then create the crossfilter.
Monitor children of a Firebase ref
In that case, the best construct is:
var quakes = new Firebase('https://myfirebase.firebaseIO.com/quakes');
var quakeCount = 0;
quakes.on('child_added', function (snapshot) {
var quake = snapshot.val();
quakeCount++;
console.log("quakeCount="+quakeCount+", FID="+quake.FID);
});
quakes.on('child_removed', function (old_snapshot) {
var quake = old_snapshot.val();
quakeCount--;
console.log("quakeCount="+quakeCount+", removed FID="+quake.FID);
});
With this code construct you're actively listening for quakes that are added and removed. You'll still have to keep an array of all the quakes, which you then modify in child_added, child_changed and child_removed.
How they compare
When you first run the code, monitoring for children will result in the same data as the on('value', construct. But when children are added/removed later on('value', will receive all quakes again, while on('child_added', and on('child_removed', will only be called for the quake in question.