ionic 3 alert button handler async issue - http

I am currently applying code on an error from an http.post call.
this.http.post('api here', {'email':this.username})
.subscribe(response => {
if(response === true){
localStorage.setItem('Username', this.username);
this.navCtrl.push(Page_1);
},
(error) => {
if(error == '404'){
let alert = this.alertCtrl.create({
title:'',
message:'',
buttons: [
{
text:'no',
handler: () => {
console.log('no clicked');
}
},
{
test:'yes',
handler: () => {
localStorage.setItem('Register_User',
this.username);
this.navCtrl.push(Page_2);
}
}
]
});
alert.present();
}}
})
So the problem i am having above, is that when i get a 404 error from the server and I want to direct them to page 2, it does not set the local storage register_username. My guess is, that this is an async thing, and its pushing to the page before it can set the storage. How do i resolve this?

If localStorage.setItem is Promise, then
handler: () => {
localStorage.setItem('Register_User', this.username)
.then(()=>{this.navCtrl.push(Page_2);})
}

Related

react-native-push-notification's configure method is not return data. Data is coming null . How can i fix it?

react-native-push-notification's configure method is not return data. Data is coming null .Here is my code
React.useEffect(() => {
PushNotification.configure({
onNotification(notification) {
if (notification.userInteraction) {
console.log(notification);
console.log('hi');
}
var nottype = notification.data.actionId;
var notid = notification.data.id;
console.log(notid);
AsyncStorage.setItem('actionId', nottype);
AsyncStorage.setItem('orderId', notid);
},
});
}, []);
you are using react-native-push-notification this library is not the best to handle notification. instead you can use #notifee/react-native to configure this for notification. this is very easy to use and do not need native code configuration.
to create a group or single channel
// Create a group
await notifee.createChannelGroup({
id: 'personal',
name: 'Personal',
});
// Assign the group to the channel
await notifee.createChannel({
id: 'comments',
name: 'New Comments',
groupId: 'personal',
});
here is a sample
import notifee, {
AndroidBadgeIconType,
EventType,
TriggerType,
} from '#notifee/react-native';
const onDisplayNotification = async (item, distance, message) => {
try {
await notifee.requestPermission();
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
});
await notifee.displayNotification({
title: `You are getting ${message} ${
message == 'Close' ? 'to' : 'from'
} ${item.name}`,
body: `You are ${distance} M away form ${item.name}`,
android: {
channelId,
actions: [
{
title: 'Close',
pressAction: {
id: 'stop',
},
},
],
smallIcon: 'ic_launcher',
pressAction: {
id: 'default',
},
},
});
} catch (e) {
console.error(e, 'ERRORORORORORORO');
}
};
here is the event with which you can interreact with them .
useEffect(() => {
return notifee.onForegroundEvent(({ type, detail }) => {
switch (type) {
case EventType.DISMISSED:
console.log('User dismissed notification', detail.notification);
break;
case EventType.PRESS:
console.log('User pressed notification', detail.notification);
break;
}
});
}, []);

Firebase signInWithRedirect() not preserving Vue route params

I have a Pricing page which has a pricing table and does the following to redirect to a Sign Up page with a route param which determines which price (product) the user picked:
methods: {
subscribe(price) {
this.loading = true;
if (!this.loggedIn) {
this.$router.push({ name: "Sign Up", params: { price: price } });
}
},
},
In the Sign Up component, it will console log the correct price from the route param in mounted , but after the signIn with google happens and it redirects to the Checkout component, the route param price is lost:
mounted: function () {
const googleAuth = new firebase.auth.GoogleAuthProvider();
if (!this.loggedIn) {
firebase.auth().signInWithRedirect(googleAuth);
firebase
.auth()
.getRedirectResult()
.then((result) => {
this.$router.push({ name: "Checkout", params: { price: this.$route.params.price } });
console.log(result);
})
.catch((error) => {
console.log(error);
});
firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.loggedIn = true;
} else {
// Show sign in screen with button above.
}
});
}
},

How can I override the client's state with the server's state in vue3 ssr?

When I was building vue3ssr recently, everything went smoothly, but the store data on the server side could never cover the store data on the client side. The following is my code, please help me to see where there is a problem
// entry-client.js
if (window && window.__INITIAL_STATE__) {
store.replaceState(window.__INITIAL_STATE__);
}
router.isReady().then(() => {
app.mount('#app')
})
<script>
<template>
<div class="home">
<h1>This is Home</h1>
<h2>ssr msg: {{ msg }}</h2>
</div>
</template>
<script setup>
import useStore from "#/store";
import { computed } from "vue";
const store = useStore();
const msg = computed(() => { // => msg: ''
return store.state.msg;
});
// console.log("store", store);
</script>
<script>
// views/home.vue
export default {
asyncData: (store) => {
return store.dispatch("asyncSetMsg");
},
};
</script>
</script>
// store/index.ts
export default function useStore() {
return createStore({
state: {
msg: "",
},
getters: {},
mutations: {
SET_MSG(state, payload) {
state.msg = payload;
},
},
actions: {
// store/index.ts
asyncSetMsg({ commit }) {
return new Promise<void>((resolve, reject) => {
setTimeout(() => {
commit("SET_MSG", "This is some msg in ssr");
resolve();
}, 300);
});
},
},
modules: {},
});
}
// entry-server.js
Promise.all(componentArr).then(() => {
console.log('store.state', store.state); // => {msg: 'This is some msg in ssr'}
html += `<script>window.__INITIAL_STATE__ = ${replaceHtmlTag(JSON.stringify(store.state))}</script>`
resolve(html);
}).catch(() => {
reject(html)
})
The above is the relevant code The following is the running result, I tried to print on the server side and the client side, the result is the normal output on the server side, but there is no data on the client sid

how to unsubscribe () a firebase collection in a vue.js component

In a vuejs component which dynamically retrieves data with firebase I would like to unsubscribe when I quit the component.
In the firebase documentation indicates that you must use the unsubscribe() function; to stop listening to the collection.
Unfortunately, this function cannot be used directly because it is declared undefined.
Here is the component code:
<script>
import db from "../../firebase/init";
let subscribe;
export default {
// ...
beforeDestroy() {
// Don't work form me !!!
unsubscribe();
},
methods: {
async getMyCollection() {
try {
subscribe = await db.collection("myCollection");
subscribe.onSnapshot(snapshot => {
snapshot.docChanges().forEach(change => {
// Do something
}
});
});
} catch (error) {
console.log(error);
}
}
}
</script>
thanks for the help
Its because you have not defined the unsubscribe anywhere. Please check the code below.
<script>
import db from "../../firebase/init";
let unsubscribe;
export default {
// ...
beforeDestroy() {
unsubscribe();
},
methods: {
async getMyCollection() {
try {
unsubscribe = await db.collection("myCollection")
.onSnapshot(snapshot => {
snapshot.docChanges().forEach(change => {
// Do something
}
});
});
} catch (error) {
console.log(error);
}
}
}
</script>

Cordova SQLite: database already open: data.db

I am trying to implement a chat app in Ionic 2 and I use SQLite.
I am however, getting the following error when I execute a executeSql on the database.
TypeError {stack: (...), message: "Cannot read property 'executeSql'
of undefined"}
But when I open the databse each transaction, I don't get the above error, but get the following warning:
database already open: data.db
I have been reading the Ionic and Cordova documentation, but cannot seem to understand what I am doing incorrect. If anyone can advise, I would appreciate it.
chatsStorageService.ts
public openDatabase(): Promise<Array<Message>> {
let promise: Promise<Array<Message>> = new Promise<Array<Message>>(resolve => {
console.log('openDatabase: ', this.database);
if (this.database && this.database != null) {
return Promise.all([this.refreshChats(this.database), this.refreshMessages(this.database)]).then(() => {
resolve(this.messages);
});
} else {
this.database = new SQLite();
this.database.openDatabase({
name: "data.db",
location: "default"
}).then(() => {
return Promise.all([this.refreshChats(this.database), this.refreshMessages(this.database)]).then(() => {
resolve(this.messages);
});
}, (error) => {
console.log("OPEN ERROR: ", error);
});
}
});
return promise;
}
public refreshChats(db: any): Promise<Array<Chat>> {
let promise: Promise<Array<Chat>> = new Promise<Array<Chat>>(resolve => {
return db.executeSql("SELECT * FROM chats", [])
.then((chatData) => {
let promises: Array<any> = [];
this.chats = [];
if (chatData.rows.length > 0) {
for (var i = 0; i < chatData.rows.length; i++) {
promises.push(this.populateChat(db, chatData.rows.item(i)));
}
}
return Promise.all(promises).then(() => {
resolve(this.chats);
});
})
.catch(error => {
console.log("ERROR REFRESHING CHATS: " + JSON.stringify(error));
console.log(error);
});
});
return promise;
}

Resources