such empty alert with jsx / react alternatives - javascript

So I was thinking I found a great way to alert users that the array is empty and there's nothing to display but actually my technique is not well implemented and only works onFocus or page reload, I put the function on componentDidMount()
componentDidMount = () => {
this.setState({loading: true})
const { currentUser } = fire.auth();
fire.database().ref(`/master/${currentUser.uid}/feed/sponsors/`)
this.setState({
sponsorsList:sponsorsList,
}, () => {
if (this.state.sponsorsList.length === 0)
this.setState({loading: false, empty: true})
});
});
}
This works but such empty text in the view still appears after I push something to the array, how do I trigger that .length function ?
{this.state.empty ? <h6 class='mb-3'>Such empty!</h6> : null }
Please someone suggest a better alternative.

I think you need to add else logic:
if (this.state.sponsorsList.length === 0) {
this.setState({ loading: false, empty: true })
} else { // Here are the additions
this.setState({ loading: false, empty: false })
}
Oh, then you can write:
{this.state.empty && <h6 class="mb-3">Such empty!</h6>}
Hope it helps :)

Related

Angular: Select checkbox on another checkbox selection ( dynamic form control )

I'm new to angular.
I have this UI. I wanted to make Bill To checkbox checked if any one (Address, Email or Phone) of the checkbox is checked. I'm using dynamic form control for checkbox.
code snippet: This solution didnt work , as combineLatest is emitting only when all the three checkboxes get selected
combineLatest([this.form.customerInfo.address.valueChanges(),
this.form.customerInfo.email.valueChanges(),
this.form.customerInfo.phone.valueChanges()])
.subscribe((formValues)=>{
if (formValues.every((value) => value === false || value === undefined)) {
this.form.customerInfo.billTo.setValue(false)
}
else {
this.form.customerInfo.billTo.setValue(true)
}
});
this.form.customerInfo.billTo.valueChanges().pipe(distinctUntilChanged()).subscribe(value =>{
// if billTo is false or unchecked- unchecked all
if(!value){
this.form.customerInfo.address.setValue(value);
this.form.customerInfo.phone.setValue(value);
this.form.customerInfo.email.setValue(value);
}
})
another solution: it's a bit complicated
combineLatest([
this.form.customer.address.valueChanges().pipe(startWith(false)),
this.form.customer.phone.valueChanges().pipe(startWith(false)),
this.form.customer.email.valueChanges().pipe(startWith(false)),
])
// adding debounce until we can listen for form changes and patch multiple form values simultaneously
.pipe(debounceTime(100))
.subscribe(([address, phone, email]) => {
if ((address || phone || email) && !this.form.customerInfo.billTo.value) {
// one of the nested values is true, and billTo is false, make billTo true
this.form.customer.billTo.setValue(true);
}
});
// when customer toggle billTo to false, we set all children to false
this.form.customer.billTo
.valueChanges()
.pipe(filter((value) => value !== true))
.subscribe(() => {
const address = this.form.customer.address.value;
const phone = this.form.customer.phone.value;
const email = this.form.customer.email.value;
// if any of the nested values are true, set them to false
if (address) {
this.form.customer.address.setValue(false);
}
if (phone) {
this.form.customer.phone.setValue(false);
}
if (email) {
this.form.customer.email.setValue(false);
}
});
Can anyone tell how to improve this? Thanks in advance.

Not able to perform 2 actions on the same component when hardware back button is pressed in react-native,below are the code regarding the backhandler

backAction = () => {
if (this.props.navigation.isFocused() && !this.state.otpScreen) {
this.setState({ showLoginScreen: true });
return true;
} else if(this.state.showLoginScreen) {
this.props.navigation.dispatch(CommonActions.reset({
index: 0,
routes: [
{ name: 'Login' },
],
}))
return false;
}
};
the code above is for action that should be done by the hardware back press, at first it should show the one screen and on the second press it should exit the app, both otp screen and login screen are on the same component, I'm just hiding based on the condition ...
at the first time it is working as per the condition but for the second time it's not.
componentDidMount() {
this.focusListener = this.props.navigation.addListener('focus', () => {
this.setState({
mobile: '',
showLoginScreen: true,
});
});
this.getDataFromStorage();
AsyncStorage.setItem('countryCode', '+91');
BackHandler.addEventListener(
"hardwareBackPress",
this.backAction
);
}
componentWillUnmount() {
clearInterval(this.interval)
BackHandler.addEventListener('hardwareBackPress', () => { return false })
}
can anyone pls help me how to do this,thanks in Advance
I guess your problem is that you can't access the 'current' value of a state inside a listener.
More Details here
Try to use a Reference instead of a state

Infinite scroll vuejs fired more than once

I'm trying to implement an infinite scroll in my vue chrome extension. I have this code but the problem is that when the page bottom is reached, the ajax call to fetch new data is fired more than once. How i can fix?
mounted() {
this.$store.commit('preloader', false)
window.onscroll = () => {
if( window.scrollY + window.innerHeight >= document.body.scrollHeight ){
console.log('fired')
this.nextPageLoaded = false
this.nextPage()
}
}
},
methods: {
nextPage() {
console.log('Loading next page')
axios.get('https://localhost:8080/api/media')
.then( (response) => {
console.log(response.data)
this.$store.commit('profileMedia', response.data.media)
this.nextPageLoaded = true
})
}
}
I've tried by setting a variable nextPageLoad to true after data are loaded and on false when the scroll event reach the bottom but not work as expected. Any solution will be appreciaetd
Perhaps it's a typo but I don't see that you are actually using the nextPageLoaded property as a flag in the if statement.
It should be something like
mounted() {
this.$store.commit('preloader', false)
window.onscroll = () => {
if ( (window.scrollY + window.innerHeight >= document.body.scrollHeight)
&& !this.nextPageLoaded) {
console.log('fired')
this.nextPageLoaded = true
this.nextPage()
}
}
},
methods: {
nextPage() {
console.log('Loading next page')
axios.get('https://localhost:8080/api/media')
.then( (response) => {
console.log(response.data)
this.$store.commit('profileMedia', response.data.media)
this.nextPageLoaded = false
})
}
}
Also have in mind that I switched the values of the nextPageLoaded property assignments because I think it's more intuitive this way (assigns to true immediately after triggering the nextPage method, assigns to false after ending the AJAX call).

React function loose state on second try

this code works properly on first and third try, there's always a step where it bugs and send no data to the db, it ruin my business logic every time, I tried with and without page reload got the same results
apiCall = e => {
e.preventDefault();
window.scrollTo(0, 0);
this.setState({ loading: true });
const { currentUser } = fire.auth();
let userEmail = currentUser.email;
let userUnderscore = userEmail.replace(/\./g, '_');
let intervalMS = this.state.interval * 60000;
let url = `https://url.com/api/v1/${userUnderscore}/${this.state.urlTask}?url=${this.state.urlTask}&width=${this.state.width}&interval=${intervalMS}&user=${userUnderscore}&running=true`;
if (this.state.interval >= 1 && this.state.urlTask !== "") {
fetch(url)
}
else {
this.setState({ addURLError: true, loading: false });
}
this.setState({ addURL: true, addURLError: false });
fire.database().ref(`/master/users/${userUnderscore}/setup/`)
.update({
running: true,
interval: this.state.interval,
url: this.state.urlTask,
});
setTimeout(
function () {
this.setState({ addURL: false, running: true });
window.location.reload();
}.bind(this), 2000
);
}
...
<Button color='black' onClick={this.apiCall} animated='vertical' type='submit'>
EDIT
The function and the db actually get updated, the issue is that on second try the state is empty even if the form hold values
I fixed the issue by reloading the app before any attempt of executing the function, that way there's always a fresh state to be used : window.location.reload();

Displaying backend responses on the webpage

I'm new to this, please be kind!
How do I transfer the value of the object that was returned to me in the console to the webpage? As of now, the balance value is in the console but it is not displayed on the page.
edit: If I wish to display the objects in the console separately, do I use myObj.key? eg. I want to display the value of balance on the left and the value of block on the right of my webpage, do I use myObj.balance and myObj.block ?
attached a screenshot of my browser
This is my code, do guide me, thank you!
<template>
<div class="box-card">
<p class="title-text">余额</p>
<p class="number-text">{{Balance}}</p>
</div>
</template>
<script>
export default {
data() {
return {
userId: 0,
// page config
currentPage: 1,
total: 0,
pageSize: 20,
userBalance: [],
Balance: '',
}
},
watch: {},
mounted() {
this.userId = this.$route.query["user_id"];
this.userId = 41;
this.getUserBalance();
this.getUserIncomeRecord();
console.log('hello');
},
methods: {
pageChange(val) {
this.currentPage = val;
},
getUserBalance() {
Core.Api.User.getUserBalance(this.userId).then(res => {
console.log(res);
res == this.Balance;
})
},
</script>
EDITED: If you want to print in a element with certain ID instead of console.log("WHAT YOU WANT TO PRINT") use this:
document.getlementById("YOUR ELEMENT ID HERE").innerHtml("WHAT YOU WANT TO PRINT");
If you use Jquery this is equivalent to the above code:
$("#ELEMENT ID HERE").html("WHAT YOU WANT TO PRINT");
make a slight change:
getUserBalance() {
Core.Api.User.getUserBalance(this.userId).then(res => {
console.log(res);
this.Balance = res;
})
},

Categories

Resources