I would like to access the node "status" and check: if false writes data, if true returns error alert.
I used the code:
var reference_value_of_counter = firebase.database().ref('contador/valor');
var reference_to_increment_counter = firebase.database().ref('contador/valor');
var reference_status_attendance = firebase.database().ref('agendamentos/primeiro-horario/status');
var reference_to_data_register = firebase.database().ref('agendamentos/primeiro-horario/');
if (reference_status_attendance.once('value', snap => snap.val() == false)) {
reference_value_of_counter.once('value', snap => reference_to_increment_counter.set(snap.val()+1));
reference_to_data_register.update({nome : 'isaac', sobrenome : "menezes", status: true});
}
else {
alert("sorry");
}
if (reference_status_attendance.once('value', snap => snap.val() == false))
This statement is not correct. once function wouldn't return the value that you return from your callback. You need to access the value and perform the if/else inside the callback. I haven't tested the below code but it should work or at least give you an idea of what needs to be done.
reference_status_attendance.once('value', snap => {
if(snap.val() == false) {
reference_value_of_counter.once('value', snap => reference_to_increment_counter.set(snap.val()+1));
reference_to_data_register.update({nome : 'isaac', sobrenome : "menezes", status: true});
}
else {
alert("sorry");
}
})
See Firebase Documentation
var reference_to_data_register = firebase.database().ref('agendamentos/primeiro-horario/');
reference_to_data_register.once('value')
.then(function(dataSnapshot) {
if(dataSnapshot.val().status){
//do this if status is true
} else {
// do this is status is false
}
});
Related
const eventSeatSelectCallback = (
SeatPrice,
FlightNumber,
SegmentKey
) => {
var postObject = { ...state.post };
postObject.IsSeatSelected = true;
postObject.AirPassengerList.filter(
(x) =>
x.FlightNumber == FlightNumber.toString() &&
x.SegmentKey.toString() == SegmentKey.toString() &&
x.IsSelected == true
)[0].SeatPrice = SeatPrice;
`
dispatch({ type: "UPDATE_SEATFORPASSENGER", payLoad: postObject });
};
The line above is giving error in the console as
Uncaught TypeError: Cannot set properties of undefined (setting 'SeatPrice')
I am trying to set the value of AirPassengerList.SeatPrice to SeatPrice
I want to to set the value of Object AirPassengerList.SeatPrice to the value of paramter SeatPrice
May be you can update the element by index
const eventSeatSelectCallback = (
SeatPrice,
FlightNumber,
SegmentKey
) => {
var postObject = { ...state.post };
postObject.IsSeatSelected = true;
const passengerIndex = postObject.AirPassengerList?.findIndex(
(x) =>
x.FlightNumber == FlightNumber.toString() &&
x.SegmentKey.toString() == SegmentKey.toString() &&
x.IsSelected == true
);
// update if item is found
if (passengerIndex !== -1) {
postObject.AirPassengerList[passengerIndex].SeatPrice = SeatPrice;
// do you need to updated this only after price update
// dispatch({ type: "UPDATE_SEATFORPASSENGER", payLoad: postObject });
}
dispatch({ type: "UPDATE_SEATFORPASSENGER", payLoad: postObject });
};
Hope it helps
I have an object like this:
let obj = {'machine1':{'err':'404', switch:false},
'gadget1':{'err':'404', switch:true}}
Would not pass validation. => return false
let obj2 = {'machine2':{'err':'404', switch:false},
'gadget2':{'err':null, switch:true}}
Would pass validation. => return true
I want to return true when every key in the object in which the switch is set to true does not have any errors (see obj2). (For machine2 the '404' error does not matter, because the switch is set to false.)
I tried something like that, but didn't get far.
function try() {
for (x in obj) {
obj[x].filter(x=>y.switch === true)
}
}
Thanks for reading!
you could do something like the follow:
const test = obj => Object.keys(obj).every(k => !obj[k].switch || obj[k].err === null)
So you check if every key in the object has switch set to false or the err equal to null.
You can do it by usign entries and every helpers of Array, like this:
let obj = {
'machine1': {
'err': '404',
switch: false
},
'gadget1': {
'err': '404',
switch: true
}
}
let obj2 = {
'machine2': {
'err': '404',
switch: false
},
'gadget2': {
'err': null,
switch: true
}
};
const validate = (data) => {
return Object.entries(data).every(([key, value]) => !value.switch || value.err === null)
}
console.log(validate(obj));
console.log(validate(obj2));
Did you mean something like that?
let obj={
1:{
'machine':{'err':'404', switch:false},
'gadget':{'err':'404', switch:true}
},
2:{
'machine':{'err':'404', switch:false},
'gadget':{'err':null, switch:true}
}
}
I changed the facility a bit to make it easier.
var n=1;
while (n<=2) {
if(obj[n].machine.switch==true){
if(obj[n].machine.err!='404')
console.log('SUKCES')
else console.log('ERROR 1')
}
else console.log('ERROR 0')
if(obj[n].gadget.switch==true){
if(obj[n].gadget.err!='404')
console.log('SUKCES')
else console.log('ERROR 1')
}
else console.log('ERROR 0')
n++;
}
Results:
ERROR 0
ERROR 1
ERROR 0
SUKCES
I need to determine the status of a parent object based on 2 variables of each of its children. I came up with a working solution, but this includes a nested "if-else if-else". Needless to say, it doesn't look very elegant.
I was wondering if there is a way to simplify this. I have muddled around with some map/reduce code, but did not get to anything that is more elegant than the code below.
const parent = {
children: [{
connected: true,
online: true
},
{
connected: true,
online: true
}
]
}
// all online & all connected => connected
// all online & some connected => partially disconnected
// all online & none connected => disconnected
// some online => partially offline
// none online => offline
const onlineArr = parent.children.map(c => c.online);
const connectedArr = parent.children.map(c => c.connected);
let status;
if (!onlineArr.includes(true)) {
status = 'Offline';
} else if (!onlineArr.includes(false)) {
if (!connectedArr.includes(true)) {
status = 'Disconnected';
} else if (!connectedArr.includes(false)) {
status = 'Connected';
} else {
status = 'Partially disconnected';
}
} else {
status = 'Partially offline';
}
console.log(status);
I'd just extract the all/some/none check into a function:
const overAll = (array, key, value, /*results in */ all, some, none) =>
array.every(it => it[key] === value) ? all : (array.some(it => it[key] === value) ? some : none);
Then it is as easy as:
const status = (
overAll(parent.children, "online", true, undefined, "Partially offline", "Offline") ||
overAll(parent.children, "connected", true, "Connected", "Partially connected", "not connected")
);
But your if/else is already quite clean IMO :)
I have modal component with form. I want to inform fields of this form that form data was successfully sent to database and clear its fields.
Component code:
//ItemModal.js
addItem(e) {
e.preventDefault();
const item = {
id: this.props.itemsStore.length + 1,
image: this.fileInput.files[0] || 'http://via.placeholder.com/350x150',
tags: this.tagInput.value,
place: this.placeInput.value,
details: this.detailsInput.value
}
console.log('addded', item);
this.props.onAddItem(item);
this.fileInput.value = '';
this.tagInput.value = '';
this.placeInput.value = '';
this.detailsInput.value = '';
this.setState({
filled: {
...this.state.filled,
place: false,
tags: false
},
loadingText: 'Loading...'
});
}
...
render() {
return (
<div className="text-center" >
<div className={"text-center form-notification " + ((this.state.loadingText) ? 'form-notification__active' : '' )}>
{(this.state.loadingText) ? ((this.props.loadingState === true) ? 'Item added' : this.state.loadingText) : '' }
</div>
)
}
action.js
export function onAddItem(item) {
axios.post('http://localhost:3001/api/items/', item )
.then(res => {
dispatch({type:"ADD_ITEM", item});
dispatch({type:"ITEM_LOADED", status: true});
})
}
helper.js
else if (action.type === 'ITEM_LOADED') {
const status = action.status;
return {
...state,
isItemLoaded: status
}
}
Currently I have few issues with my code:
1. field are clearing right after click, but they should clear after changing state of loadingState. I tried to check it in separate function on in componentWillReceiveProps whether state is changed and it worked, but I faces another problem, that after closing this modal there were errors, that such fields doesn't exist.
2. loadingText should become '' (empty) after few seconds. Tried same approach with separate function and componentWillReceiveProps as at first issue.
In constructor keep a copy of your initial state in a const as follows:
const stateCopy = Object.create(this.state);
When your ajax request completes, in the sucess callback you can reset the state with this copy as follows:
this.setStae({
...stateCopy
});
One of the few ways to achieve this is to use async await which will resolve the promises and then return the value after that you can clear the values
1st approach using the async await
Here is the example
handleSubmit = async event => {
event.preventDefault();
// Promise is resolved and value is inside of the response const.
const response = await API.delete(`users/${this.state.id}`);
//dispatch your reducers
};
Now in your react component call it
PostData() {
const res = await handleSubmit();
//empty your model and values
}
Second approach is to use the timer to check the value is changed or not
for this we need one variable add this to the service
let timerFinished=false;
one function to check it is changed or not
CheckTimers = () => {
setTimeout(() => {
if (timerFinished) {
//empty your modal and clear the values
} else {
this.CheckTimers();
}
}, 200);
}
on your add item change this variable value
export function onAddItem(item) {
axios.post('http://localhost:3001/api/items/', item)
.then(res => {
timerFinished = true;
dispatch({
type: "ADD_ITEM",
item
});
dispatch({
type: "ITEM_LOADED",
status: true
});
})
}
and here is how we need to call it.
PostData = (items) => {
timerFinished = false;
onAddItem(items);
this.CheckTimers();
}
If you check this what we done is continuously checking the variable change and emptied only once its done.
One thing you need to handle is to when axios failed to post the data you need to change the variable value to something and handle it, you can do it using the different values 'error','failed','success' to the timerFinished variable.
I'm using React Native and firebase for the application, where I'm using 'on' for listening to database changes, but whenever data is updated, my data doubles (getting duplicates of every object). I tried resetting the data before forEach loop but it returns the empty data on the last iteration. I was using array earlier and then I tried using Set but still the same result. Any help will be appreciated. Thanks
Here is my code:
friendPost = () => {
let that = this;
let res = new Set();
firebase.database().ref("/Manifest User/"+this.state.currentUsername.charAt(0).toUpperCase()+ "/"+
this.state.currentUsername+"/Friends").on("value", function (snapshot) {
// let result=[];
snapshot.forEach(function (childSnapshot) {
if(childSnapshot.key !== 'Friend Requests'){
res=[];
firebase.database().ref("/Manifest User/"+childSnapshot.key.charAt(0).toUpperCase()+"/"+childSnapshot.key
+"/Profile Posts/").on("value", function (postSnapshot) {
postSnapshot.forEach(function(miniSnapshot){
if(miniSnapshot.key !== '~default') {
let url;
let urlTemp = miniSnapshot.val().post.match(/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/);
if (urlTemp !== null){
url = urlTemp[0];
if (urlTemp[0].includes("youtu")) {
url = "https://www.youtube.com/embed/"+urlTemp[0].substr(urlTemp[0].lastIndexOf("/")+1);
}
else if (urlTemp[0].includes("vimeo.com")){
url = "https://player.vimeo.com/video/"+urlTemp[0].substr(urlTemp[0].lastIndexOf("/")+1);
}
}
let postString = miniSnapshot.val().post
.replace(/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/, '');
res.push({
postDate: miniSnapshot.key,
postImage: miniSnapshot.hasChild('postImage') ? miniSnapshot.val().postImage : '',
post: postString,
username: miniSnapshot.hasChild('postUserName') ? miniSnapshot.val().postUserName : '',
comments: miniSnapshot.hasChild('postComments') ? miniSnapshot.val().postComments : [],
likes: miniSnapshot.hasChild('postLikes') ? miniSnapshot.val().postLikes : [],
url: url,
actualPostString: miniSnapshot.hasChild('post') ? miniSnapshot.val().post : '',
});
}
});
// alert(JSON.stringify(res))
that.setState({friendPosts: Array.from(res)});
}.bind(this));
}
});
})
};
A reason for this to be happening is your component re-rendering. The code where you are calling this function is called twice i.e. on a re-render.