I am trying to create a to-do app in react-redux, in that I want to compare date and time if date and time exceed the current date, then I want to pass data to pastReminders otherwise remain in upcoming reminders how should I update the react part and in this I am required to update state in redux also.
I am not getting the approach for this. I have reminders on an array of the object where all my data is stored.Till now I have done this:
const { reminders } = this.props;
reminders.forEach(function (data) {
var userTime = data.scheduled_datetime;
var now = moment().format();
if(userTime > now ) {
var userId = data.id;
console.log(userId);
}
Related
This is the database structure i have i want to get logged in user data.
i want to make table of data: Columns: Date,Status
Also i want to make percentage piechart wheel by calculating success and failure rate. but not able to get data from firebase.
I tried this but not working. I'm able to log in log out successfully. I'm also able to add data in firebase only once per date.
I'm just not able to fetch and show in table.
Here's what i tried:
`
// Get the user's attendance records
firebase.database().ref("attendance").once("value", function(snapshot) {
// Get the attendance data
var attendanceData = snapshot.val();
var userId = firebase.auth().currentUser.uid;
// Display the attendance history
for (var email in attendanceData) {
var attendance = attendanceData[email][userId];
if (attendance) {
for (var date in attendance) {
var status = attendance[date].status;
var tr = document.createElement("tr");
tr.innerHTML = `<td>${date}</td><td>${status}</td>`;
attendanceHistoryTable.appendChild(tr);
}
}
}
});
If I understand correctly, you have a data structure like this:
attendance: {
user: {
"$uid": {
"$date": {
Status: "..."
}
}
}
}
And from this you want to show the status per date for the current user.
If that's indeed the use-case, you can do this with:
const userId = firebase.auth().currentUser.uid;
const attendanceRef = firebase.database().ref("attendance");
const userRef = attendanceRef.child("users").child(userId);
userRef.once("value", function(userSnapshot) {
userSnapshot.forEach((dateSnapshot) => {
const status = dateSnapshot.child("Status").val();
console.log(`User: ${userSnapshot.key}, Date: ${dateSnapshot.key}, Status: ${status}`);
... // TODO: add the data to the HTML as you're already doing
});
});
The main changes I made here:
This only loads the data for the current user, instead of for all users.
This code uses the built-in forEach operation of a DataSnapshot.
This code gives more meaningful names to the variables, so that it's easier to parse what is going on.
This code uses "Status" rather then status, since that's the key in your database screenshot too.
I'm on a vuejs and firebase project.
And I would like to display only the data recorded today.
But I don't know how to do it.
Can you please help me.
created() {
const dfRef = db.ref("Colis Requetes")
dfRef.orderByChild("created_at").on("value", (dataSnapshot) => {
const itemsArray = [];
dataSnapshot.forEach((childSnapshot) => {
const childData = childSnapshot.val();
const childDataKey = childSnapshot.key;
this.Colis = childData;
itemsArray.push({
id: childDataKey,
client_name: childData.client_name,
client_phone: childData.client_phone,
colis_type: childData.colis_type,
payment_method: childData.payment_method,
});
});
this.Colis = itemsArray.reverse();
});
}
The orderByChild property is for displaying data from the most recent date to the oldest date. However, I want only the recordings made today to appear on the page.
I'm on a vuejs and firebase project.
And I would like to display only the data recorded today.
But I don't know how to do it.
Can you please help me.
You'll want to use a filtering operation for that, most likely startAt.
If your created_at contains a timestamp (going forward, please include such information in your question), that'd be something like:
var start = new Date();
start.setUTCHours(0,0,0,0); // based on https://stackoverflow.com/a/8636674
const dfRef = db.ref("Colis Requetes")
dfRef
.orderByChild("created_at")
.startAt(start.getTime()) // 👈
.on("value", (dataSnapshot) => {
...
This question already has answers here:
Firebase Query Double Nested
(3 answers)
Closed 10 months ago.
I have a child that get created inside my RTDB in firebase. This happens by a webservice that sends this data to firebase via the Rest API. It happens every 10 min. The data arrives and the function picks it up when it occurs. The node hold a couple of values but specifically a device: "3523EB" value that's needed for the next part. Below is the structure of that node data:
The 'device' value here "3523EB" need to update a different table that it needs to go look for with and equalTo in the devices table. Problem is the devices table has the userID and the key. So its 2 un-known values that it needs to search through as the chils its looking for contains imei:"3523EB" and it's only that child that needs to be updated.
I've tried using ref.orderByChild("imei").equalTo(deviceRef).on("child_added", function(snapshot) {
So device:"3523EB" in sigfox table has to look for and update only the child with this in is data as imei:"3523EB" in the devices table, but the {UserId} and the {key} where the table resides in devices is unknow.
Getting the values from sigfox in the function as it hits the DB is no issue: to take the value and look for the child in devices then update that child proves to be a challenge.
exports.UpdateDeviceData = functions.database.ref('sigfox/{key}/')
.onCreate((snapshot, context) => {
const deviceRef = snapshot.val()['device'];
const batteryRef = snapshot.val()['battery'];
const speedRef = snapshot.val()['speed'];
const temperatureRef = snapshot.val()['temperature'];
const latitudeRef = snapshot.val()['latitude'];
const longitudeRef = snapshot.val()['longitude'];
const timeRef = snapshot.val()['time'];
const now = new Date().getTime();
functions.logger.log('Sigfox Data Updated for device: ', deviceRef);
var db = admin.database();
var refi = db.ref("devices/");
refi.once("value", function(snapshot) {
snapshot.forEach(function(child) {
var key = child.key;
snapshot.ref.update({
battery: batteryRef,
speed: speedRef,
temperature: temperatureRef,
lati: latitudeRef,
longi: longitudeRef,
updateTime: timeRef })
functions.logger.log('Device Key Details: ',child.val());
})
});
return null;
});
Please help...
Restuctured and it works perfectly fine now:
var db = admin.database();
var query = db.ref('devices/' + deviceRef).orderByChild("imei").equalTo(deviceRef);
query.on("child_added", function (snapshot) {
snapshot.ref.update({
battery: batteryRef,
speed: speedRef,
temperature: temperatureRef,
lati: latitudeRef,
longi: longitudeRef,
updated: now})
});
thanks to: Frank van Puffelen
async function getData(ret) {
var list = [];
const b = await firebase.database().ref('tesco').limitToFirst(20).on('value',function (snapshot) {
snapshot.forEach(function (childSnapshot) {
list.push(childSnapshot.val())
I have to push data from firebase , to Array. It takes alot of time and i have to refresh App to see data on Screen.
put the list or return of getData() in a state, so every time it has new value the component will refreshed automatically
I recently started with react (alongside react-native) and a lot of things are alien to me. I was creating an app in react native which shows cryptocurrency value in real time.
Coin cap provides web-socket connection so that the new values are automatically updated instead of fetching the entire stuff using axios.
Now, In simple HTML and javascript world, I assigned an ID to the elements and used for loop whenever the new data came from web-socket to find the value I need to update(or change).
Something like this
var socket = io.connect('https://coincap.io');
socket.on('trades', function (tradeMsg) {
var crypto = tradeMsg.coin;
for (let i=0; i<500; i++) {
var compare = cryptoSName[i].innerHTML;
if (compare == crypto) {
var oldPrice = document.getElementById('price' + i).innerHTML;
document.getElementById('price' + i).innerHTML= (tradeMsg.message.msg.price.toFixed(4));;
document.getElementById('perc' + i).innerHTML= tradeMsg.message.msg.perc + "%";
document.getElementById('pricer1' + i).innerHTML= (tradeMsg.message.msg.price.toFixed(4));;
document.getElementById('percr1' + i).innerHTML= tradeMsg.message.msg.perc + "%";
var newPrice = tradeMsg.message.msg.price;
[Question] In react I can still assign an ID to the elements but how can we do something like that (using web-socket to update data)? Also, keeping in mind how react components render (or re-render) things.
[Update] I am using Redux which stores the data in a state. Consider this
Data/state I receive from redux (through axios api call in some action)
class cryptoTicker extends Component {
componentWillMount() {
this.props.fetchCoin();
}
render() {
var CryptoData = this.props.cryptoLoaded;
let displayCrypto = CryptoData.map(el => {
return (
<CoinCard
key={el["long"]}
coinPrice = {el["price"].toFixed(2)}
/>
);
});
return (
<ScrollView>{displayCrypto}</ScrollView>
);
}
}
const mapStateToProps = state => {
return {
cryptoLoaded: state.posts.itemsSucess
}
};
export default connect(mapStateToProps, {fetchCoin})(cryptoTicker);
Note: Initially all the data is fetched through axios (ajayx) and websocket only sends changes in the fetched data
Just in case: Here is the link to coincap api's documentation
https://github.com/CoinCapDev/CoinCap.io