how to call a function after press "on action selected" in react native Toolbar - toolbar

I implemented a React native Toolbar its showing me all actions which i have given but after press on that any action it gives me error. Its entering in the function that onActionSelected But after that my Logout() , Move() any function is not working.
where i am going wrong plz help
code:
<ToolbarAndroid
title="Shopcon"
style={styles.toolbar}
actions={toolbarActions}
onActionSelected={this.onActionSelected}
/>
const toolbarActions = [
{title: 'Logout', show: 'never'},
{title: 'Got to Login', show: 'never'},
];
onActionSelected(position) {
if (position === 0) {
console.log("I am in 0");
this.Logout();
}
if (position === 1) {
console.log("I am in 1");
this.Move();
}
}
async Logout() {
console.log("fun1");
const { navigate } = this.props.navigation;
try {
await AsyncStorage.removeItem(STORAGE_KEY);
Alert.alert("Logout Success! Token:" + DEMO_TOKEN)
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
navigate("Login");
}
Move(){
console.log("fun2")
const { navigate } = this.props.navigation;
navigate("Login");
}
both are entering in onActionSelected(position) function but not entering in those other functions.
where i am going wrong please help.

Related

Flutter code in widgetsBinding.instance.addPostFrameCallback getting called multiple times

I am building a sign in functionality using bloc pattern, if the entered credentials are invalid, bloc will return a authErrorState, so I will display a invalid credentials popup as soon as the bloc return a authError State
please check the code :
if (state is IsAuthLoadingState) {
return const LoadingSpinnerWidget();
} else if (state is IsAuthenticatedState) {
WidgetsBinding.instance.addPostFrameCallback((_) {
stopTimer();
BlocProvider.of<AuthBloc>(context).add(LoadAuthStatus());
Navigator.pop(context, true);
});
} else if (state is AuthErrorState) {
WidgetsBinding.instance.addPostFrameCallback((_) {
stopTimer();
showCustomPopUp(state.message);
});
}
Bloc code :
void _onLoginUser(LoginUser event, Emitter<AuthState> emit) async {
emit(IsAuthLoadingState());
final UserLoggedInResponse userDetails =
await authRepository.handleLoginUser(event.phoneNumber, event.otp);
if (userDetails.status == "success") {
for (var item in userDetails.wishlist) {
await _localRepo.addWishlistItem(item);
}
for (var item in userDetails.cart) {
await _localRepo.addCartItem(item);
}
for (var item in userDetails.recentSearches) {
await _localRepo.addRecentSearchTerm(item);
}
await _localRepo.addPurchasedItems(userDetails.purchasedItemIds);
await _localRepo.setIsAuthenticated(
userDetails.accessToken, userDetails.userId);
emit(IsAuthenticatedState());
} else {
emit(AuthErrorState(
message: userDetails.message, content: userDetails.content));
}
}
But, the invalid credentials popup written in authErrorState is getting called multiple times.
Any help is really appreciated. Thank you.
As I didn't found any alternative options, I someone tried to manage this for now like this,
I used a bool variable called isErrorShown, and it was set to false by default,
once the code in widgetsBinding is executed, it will set the isErrorShown to true, function is widgetsBinding checks the value of isErrorShown and executes only if it is false :
else if (state is AuthErrorState) {
print("error state");
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!isErrorShown) {
stopTimer();
if (state.message ==
"user does not exits, please create user") {
Navigator.pushReplacementNamed(context, '/create-user',
arguments: CreateUserPage(
showProfile: widget.showProfile,
phoneNumber: phoneNumberController.text,
otp: otpController.text,
));
// BlocProvider.of<AuthBloc>(context).add(LoadAuthStatus());
// Navigator.pushNamed(context, '/create-user');
} else {
showCustomPopUp(state.message);
}
isErrorShown = true;
}
});

Ionic 4, Firebase-x and FCM Push notification with action buttons

I am trying to add action buttons to the push notifications sent via the firebase admin SDK to my Ionic 4 app using the Firebase-X native plugin to handle push notifications. My app is running on android and ios.
Here's my current script that sends me successfully a push notification:
exports.sendDebugPush = functions.pubsub.schedule('* * * * *').onRun((context) => {
let promises: Promise<any>[] = [];
return admin.database().ref('/users/******').once("value")
.then( user => {
let todos = [];
for(let key in user.val().nextActions) {
if(user.val().nextActions[key].active != false) {
let todo = user.val().nextActions[key]
todo['todoid'] = key;
todos.push(todo);
}
}
if(todos.length > 0) {
//currently we pick a random todo, later on the one with the highest priority
//todos.sort((a, b) => (a.priority/1 < b.priority/1) ? 1 : -1);
let randomTodo = todos[Math.floor(Math.random()*todos.length)]
let payload: any = {
notification: {
title: "Gossik",
body: "Hoiiiii " + new Date().toISOString()
},
data: {
title: "Gossik",
body: "Hoiiiii " + new Date().toISOString(),
target: 'todo',
todoid: randomTodo.todoid
}
};
Object.values(user.val().devices).forEach( (device) => {
promises.push(admin.messaging().sendToDevice(String(device), payload));
});
}
return Promise.all(promises)
.then( () => {
console.log('success!');
})
.catch( error => {
console.log('failed :(');
console.log(error);
});
});
});
Of course, without action buttons. And this function handles the push notifications in my app (this.firebase = FirebaseX plugin imported from 'import { FirebaseX } from "#ionic-native/firebase-x/ngx";'):
initPushNotifications() {
this.firebase.getToken().then(token => {
this.db.saveDeviceToken(this.auth.userid, token);
});
this.firebase.onMessageReceived().subscribe(data => {
if(!data.target) {
let title = '';
if(data.title) {
title = data.title;
} else if(data.notification && data.notification.title) {
title = data.notification.title;
} else if(data.aps && data.aps.alert && data.aps.alert.title) {
title = data.aps.alert.title;
}
let body = '';
if(data.body){
body = data.body;
} else if(data.notification && data.notification.body){
body = data.notification.body;
} else if(data.aps && data.aps.alert && data.aps.alert.body){
body = data.aps.alert.body;
}
this.alertCtrl.create({
message: title + ' ' + body,
buttons: [
{
text: "Ok"
}
]
}).then( alert => {
alert.present();
});
} else {
this.goToToDoPage(data.todoid);
}
});
}
It does this also successfully. I achieved to handle the click on the push notification such that it redirects to my To-Do page for this kind of push notification (one with a 'target' property). But now I'd like to add two action buttons 'Start' and 'Skip' on the push notification to start or skip the corresponding to-do. To be clear, I am talking about a background push notification, so the app is not open. The user then gets a standard push notification on his phone and there I'd like two action buttons to take an action without opening the app itself.
I tried various things with the payload to first even show me action buttons, but didn't achieve it. For example, the following is not working for me:
let payload: any = {
notification: {
title: "Gossik",
body: "Hoiiiii " + new Date().toISOString()
},
data: {
title: "Gossik",
body: "Hoiiiii " + new Date().toISOString(),
target: 'todo',
todoid: randomTodo.todoid,
"actions": [
{ "icon": "approve_icon", "title": "APPROVE", "callback": "AppComponent.approve", "foreground": true},
{ "icon": "reject_icon", "title": "REJECT", "callback": "AppComponent.reject", "foreground": true}
]
}
};
Thanks a lot in advance for your help and let me know if something is still unclear. :)

navigation after AsyncStorage.setItem: _this3.navigateTo is not a function

Currently, I am implementing a chat. After user pressed a chat button, the app will navigate the user to the Chat component. The chat content will simply store in firebase and chatId is needed to identify which chat belongs to the user.
Since I don't know how to pass props during navigation, I decided to save the CurrentChatId in AsyncStorage. After navigated to the Chat component, it will get the CurrentChatId from AsyncStorage so that I can map the chat content with the firebase.
However, I got the error _this3.navigateTo is not a function with code below:
let ref = FirebaseClient.database().ref('/Chat');
ref.orderByChild("chatId").equalTo(chatId).once("value", function(snapshot) {
chatId = taskId + "_" + user1Id + "_" + user2Id;
if (snapshot.val() == null) {
ref.push({
chatId: chatId,
taskId: taskId,
user1Id: user1Id,
user2Id: user2Id,
})
}
try {
AsyncStorage.setItem("CurrentChatId", chatId).then(res => {
this.navigateTo('chat');
});
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
}
The function navigateTo is copied from the demo app of NativeBase
import { actions } from 'react-native-navigation-redux-helpers';
import { closeDrawer } from './drawer';
const {
replaceAt,
popRoute,
pushRoute,
} = actions;
export default function navigateTo(route, homeRoute) {
return (dispatch, getState) => {
const navigation = getState().cardNavigation;
const currentRouteKey = navigation.routes[navigation.routes.length - 1].key;
dispatch(closeDrawer());
if (currentRouteKey !== homeRoute && route !== homeRoute) {
dispatch(replaceAt(currentRouteKey, { key: route, index: 1 }, navigation.key));
} else if (currentRouteKey !== homeRoute && route === homeRoute) {
dispatch(popRoute(navigation.key));
} else if (currentRouteKey === homeRoute && route !== homeRoute) {
dispatch(pushRoute({ key: route, index: 1 }, navigation.key));
}
};
}
You should bind this to the function that contains the try & catch. The best practice is to add this bind the constructor of the the component:
constructor(props) {
super(props);
this.myFunctoin = this.myfuction.bind(this);
}
Finally, I solved the problem. It is really because this.navigateTo('chat'); is inside function(snapshot)
ref.orderByChild("chatId").equalTo(chatId).once("value", function(snapshot) {
chatId = taskId + "_" + user1Id + "_" + user2Id;
if (snapshot.val() == null) {
ref.push({
chatId: chatId,
taskId: taskId,
user1Id: user1Id,
user2Id: user2Id,
})
}
}
try {
AsyncStorage.setItem("CurrentChatId", chatId).then(res => {
this.navigateTo('chat');
});
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
Take it out from the function will solve the problem.

Meteor Tracker autorun fires 2 times

This Meteor client code tries to make the Tracker.autorun to run once but as it appears to be that it has to run twice, once for setting and once for reactiveness.
Which is fine but it is firing 3 times. Once for setting and 2 for reacting even though the server only updated the user.profile.abc once.
To test it, I run this code in the mongodb console and the the iamge attached is what I got which confirms it fires twice.
How can I get it to run only once for responding to the changes in the users collection? Thanks
db.users.update({_id: Meteor.userId()},{$set: {'profile.ABC': ['a','b']}}).pretty()
//client
Meteor.call('cleanABC', (err) => {
if (!err) {
ABCListener();
}
});
ABCListener: () => {
Tracker.autorun(() => {
if (Meteor.userId()) {
console.log('auto run invoked');
if (Meteor.user().profile.ABC) {
const myArray = Meteor.user().profile.ABC;
//myFunction(myArray);
console.log('condition true');
} else {
console.log('condition false');
}
}
});
}
//server
'cleanABC': function() {
return Meteor.users.update({
_id: Meteor.userId()
}, {
$unset: {
'profile.ABC': ''
}
});
}
//and some where else in the code
Meteor.users.update({
_id: userId
}, {
$set: {
'profile.ABC': myArray
}
}, (err) => {
if (!err) {
console.log('just sent the array');
}
});
I think the problem is that you are just calling Tracker.autorun everytime you call the method.
I think if you change your client code to:
//client
ABCListener: () => {
Tracker.autorun(() => {
if (Meteor.userId()) {
console.log('auto run invoked');
if (Meteor.user().profile.ABC) {
const myArray = Meteor.user().profile.ABC;
//myFunction(myArray);
console.log('condition true');
} else {
console.log('condition false');
}
}
});
}
Meteor.call('cleanABC');
it should work.

Meteor - insert failed: Method not found

I have a problem with my Meteor's JS file. I get this error "insert failed: Method not found" when I try to insert any data to the database and reflect on chart. I've tried fetching data directly from db that didn't work too...
thanx in advance.
LinePeople = new Mongo.Collection("LinePeople");
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
if (Meteor.isClient) {
console.log("in LIne Client");
//LinePeople = new Mongo.Collection(null);
Template.linenvd3.rendered = function() {
var chart = nv.models.lineChart()
.margin({left: 80}) //Adjust chart margins to give the x-axis some breathing room.
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
.transitionDuration(350) //how fast do you want the lines to transition?
.showLegend(true) //Show the legend, allowing users to turn on/off line series.
.showYAxis(true) //Show the y-axis
.showXAxis(true) //Show the x-axis
;
nv.addGraph(function() {
chart.xAxis.axisLabel('Person number').tickFormat(d3.format('d'));
chart.yAxis.axisLabel('Age (years)').tickFormat(d3.format('d'));
d3.select('#lineChart svg').datum(
[{ values: LinePeople.find().fetch(), key: 'Age' }]
).call(chart);
nv.utils.windowResize(function() { chart.update() });
return chart;
});
Deps.autorun(function () {
d3.select('#lineChart svg').datum(
[{ values: LinePeople.find().fetch(), key: 'Age' }]
).call(chart);
chart.update();
});
};
Template.linenvd3.events({
'click #addDataButton': function() {
console.log(" in line addButton");
var age = getRandomInt(13, 89);
var lastPerson = LinePeople.findOne({}, {fields:{x:1},sort:{x:-1},limit:1,reactive:false});
if (lastPerson) {
console.log(" in lastPerson.. if block");
LinePeople.insert({x:(lastPerson.x + 1), y:age});
} else {
console.log(" in lastPerson.. else block");
LinePeople.insert({x:1, y:age});
}
},
'click #removeDataButton': function() {
console.log(" in line removeButton");
var lastPerson = LinePeople.findOne({}, {fields:{x:1},sort:{x:-1},limit:1,reactive:false});
if (lastPerson) {
LinePeople.remove(lastPerson._id);
}
}
});
}
if (Meteor.isServer) {
console.log("in line Server");
}
While following the Getting Started tutorial on the official meteor.js website I've had the same problem with autopublish turned on.
Turned out the issue was I created my Tasks collection inside the imports/ folder. Thus it was not implicitly imported on the server.
I had to explicitly import it on the server to solve the issue.
server/main.js
import { Meteor } from 'meteor/meteor';
import '../imports/api/tasks.js';
Meteor.startup(() => {
// code to run on server at startup
});
As you can see the import is not used by my code but is required anyways.
Thanks for the help... I actually got it worked by publishing the collection and giving it some permissions:
This code is placed in "myapp/shared/collections.js". (Placed them separately to handle all the other collections which I would add for other graphs)
lineVar = new Meteor.Collection("linenvd3");
lineVar.allow({
insert: function () {
return true;
},
update: function () {
return true;
},
remove: function () {
return true;
}
});
This code is placed in "myapp/server/publish.js"
Meteor.publish('line', function () {
return lineVar.find();
});
Then, this is modified Javascript made look more simpler and comprehensive.
if (Meteor.isClient) {
Meteor.subscribe('line');
Template.linenvd3.rendered = function() {
var chart = nv.models.lineChart()
.margin({left: 80})
.useInteractiveGuideline(true)
.transitionDuration(350)
.showLegend(true)
.showYAxis(true) //Show the y-axis
.showXAxis(true) //Show the x-axis
;
nv.addGraph(function() {
chart.xAxis.axisLabel('Person number').tickFormat(d3.format('d'));
chart.yAxis.axisLabel('Age (years)').tickFormat(d3.format('d'));
d3.select('#lineChart svg').datum(
[{ values: lineVar.find().fetch(), key: 'Age' }]
).call(chart);
nv.utils.windowResize(function() { chart.update() });
return chart;
});
Deps.autorun(function () {
d3.select('#lineChart svg').datum(
[{ values: lineVar.find().fetch(), key: 'Age' }]).call(chart);
chart.update();
});
};
}

Resources