sendbird error 400 bad request /user not found - sendbird

I am trying to play with sendbird. I am getting this error . I am trying to make sendbird api work in react.js app. I have read the documentation and it wasnt clear to me. I have looked at stackoverflow earlier replies and Thats why , i tried to create channel after i get connected to sendbird.
VM2257:1 POST https://api.sendbird.com/v3/group_channels 400 (BAD
REQUEST)
error is here p {name: "SendBirdException", code: 400201, message: "User not found."}
I am trying to implement it in react.js . Here's my code. Can someone help me out with how to rectify this error.
import React, { Component } from 'react';
import * as SendBird from 'sendbird';
import './App.css';
var sb = new SendBird({'appId': '59BEEA34-BDC7-461B-B10B-63705C8B57C2'});
class App extends Component {
componentWillMount(){
sb.connect("ankur1", function(user, error) {
if(user){
console.log("looks like connected",user)
var userIds = ['unique_user_id1', 'unique_user_id2','ankur1'];
var name = "amazing1";
sb.GroupChannel.createChannelWithUserIds(userIds, false, name, function(createdChannel, error) {
if (error) {
console.error("error is here",error);
return;
}
console.log("success",createdChannel);
});
}
else{
console.log("looks like error")
}
})
}
sm(){
console.log("button clicked",sb)
var channel = "amazing"
/*
sb.channel.sendUserMessage("that is cool", '', function(message, error){
if (error) {
console.error(error);
return;
}
console.log(message);
});
*/
}
componentDidMount(){
}
render() {
var sm = this.sm.bind(this)
return (
<div>
<h1>ankur is here </h1>
<button onClick={sm}>click here</button>
</div>
);
}
}
export default App;

I actually had a similar problem yesterday. Googling around it actually led me here. Eventually, I found a way around it.
So, the first thing I do after creating the connection to SendBird is to create a connection for that user I wish to connect to.
var sb = new SendBird({
appId: 'YOUR SENDBIRD APP ID HERE'
});
sb.connect(UNIQUE_USER_ID, function(user, error) {
connectToUser();
});
function connectToUser(){
sb.connect(YOUR_OWN_USERID, function(user, error) {
sb.GroupChannel.createChannelWithUserIds([UNIQUE_USER_ID], true, UNIQUE_USER_ID+YOUR_OWN_USERID, '', '', '', function(createdChannel, error){
$scope.chatChannel = createdChannel;
if (error) {
console.log(error);
return;
}
});
});
}
Then, you can proceed to send your messages using the createdChannel
$scope.chatChannel.sendUserMessage(YOUR_MESSAGE_HERE, '', '', function(message, error){
if (error) {
console.error(error);
return;
}
console.log(message);
});
Let me know if that works.

Related

Expo Notification Error in ios [Error: Another async call to this method is in progress. Await the first Promise.]

Please provide the following:
SDK Version: "^42.0.0",
Platforms(Android/iOS/web/all): iOS
Add the appropriate "Tag" based on what Expo library you have a question on.
Hello,
[expo-notifications] Error encountered while updating server registration with latest device push token., [Error: Another async call to this method is in progress. Await the first Promise.]
This error often occurs in expo app. And always occurs in build ios app.
Using the following code:
async function registerForPushNotificationsAsync() {
let token
if (Constants.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync()
let finalStatus = existingStatus
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync({
ios: {
allowAlert: true,
allowBadge: true,
allowSound: true,
allowAnnouncements: true,
},
})
finalStatus = status
}
if (finalStatus !== 'granted') {
console.log('noti cancel')
return
}
// token = (await Notifications.getExpoPushTokenAsync()).data
try {
await Notifications.getExpoPushTokenAsync().then((res) => {
console.log('getExpoPUshTokenAsync >> ', res)
token = res.data
})
} catch (err) {
console.log('getExpoPushTokenAsync error >> ', err)
}
} else {
Alert.alert(
'Must use physical device for Push Notifications'
)
}
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
})
}
return token
}
I have received a new credential, but I am still getting the error.

IOS Notification Permission alert does not show

SDK Version: 39.0.0
Platforms(Android/iOS/web/all): All
I am not getting accept or decline notifications permissions alert when loading my app in production.
I have tried clearing certificates and keys and allowing expo to add everything from a clean slate, but still no luck. I am starting to think maybe it’s my code which is the reason why the alert doesn’t get fired.
import Constants from "expo-constants";
import * as Notifications from "expo-notifications";
import { Permissions } from "expo-permissions";
import { Notifications as Notifications2 } from "expo";
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowAlert: true,
shouldPlaySound: true,
shouldSetBadge: false
})
});
export default class LoginScreen extends React.Component {
state = {
email: "",
password: "",
notification: {},
errorMessage: null
};
async componentDidMount() {
this.registerForPushNotificationsAsync();
//Notifications.addNotificationReceivedListener(this._handleNotification);
Notifications2.addListener(data => {
this.setState({ notification: data });
});
Notifications.addNotificationResponseReceivedListener(
this._handleNotificationResponse
);
}
_handleNotification = notification => {
this.setState({ notification: notification });
};
_handleNotificationResponse = response => {
console.log(response);
};
handleLogin = async () => {
try {
const { email, password } = this.state;
const expoPushToken = await Notifications.getExpoPushTokenAsync();
console.log(expoPushToken);
const userinfo = await firebase
.auth()
.signInWithEmailAndPassword(email, password);
console.log("user ID ", userinfo.user.uid);
await firebase
.firestore()
.collection("users")
.doc(userinfo.user.uid.toString())
.update({
expo_token: expoPushToken["data"]
})
.then(function() {
console.log("token successfully updated!");
})
.catch(function(error) {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
} catch (error) {
console.log("=======Error in login", error);
this.setState({ errorMessage: error.message });
}
};
registerForPushNotificationsAsync = async () => {
if (Constants.isDevice) {
const { status: existingStatus } = await Permissions.getAsync(
Permissions.NOTIFICATIONS
);
let finalStatus = existingStatus;
if (existingStatus !== "granted") {
const { status } = await Permissions.askAsync(
Permissions.NOTIFICATIONS
);
finalStatus = status;
}
if (finalStatus !== "granted") {
alert("Failed to get push token for push notification!");
return;
}
const token = await Notifications.getExpoPushTokenAsync();
console.log(token);
//this.setState({ expoPushToken: token });
} else {
alert("Must use physical device for Push Notifications");
}
if (Platform.OS === "android") {
Notifications.setNotificationChannelAsync("default", {
name: "default",
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: "#FF231F7C"
});
}
};
import { Permissions } from "expo-permissions";
should of been
import * as Permissions from 'expo-permissions';
Sometimes we all make simple mistakes.

How to delay http responses on errors in Angular 7

I am working on an Angular7 project and have some issues about error handling on http requests.
Here is my Login Component with two functions
export class LoginComponent implements OnInit, OnDestroy {
emailLogin1() {
this.authService.emailLogin1(this.loginForm.value).pipe(delay(1000)).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}
emailLogin2() {
this.authService.emailLogin2(this.loginForm.value).pipe(delay(1000)).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
}
}
Here is my AuthService with two functions.
export class AuthService {
constructor(private http: HttpClient) {
}
emailLogin1(values): any {
return this.http.post(environment.server + '/auth/emailLogin', values).pipe(
tap(
(response) => {
localStorage.setItem('token', response['token']);
},
(error) => {
console.log(error);
}
)
);
}
emailLogin2(values): any {
return this.http.post(environment.server + '/auth/emailLogin', values).pipe(
tap(
(response) => {
localStorage.setItem('token', response['token']);
}
),
catchError((error) => {
console.log(error);
throw error;
})
);
}
}
When I make a request to the server, if response status is successful, it waits for 1000 ms and then shows the result as expected. But if response returns an error, delay(1000) function not working and error block working immediately. I tried with and without catchError. Both working exactly the same.
The delay operator will only work on events sent through the observable via "next" notifications (in your case, this is a "success"). When an error occurs, it is sent as an "error" notification, and it skips right past your delay operator. If you want to delay the error, you should catch it, introduce a delay, and then re-throw it:
emailLogin1() {
this.authService.emailLogin1(this.loginForm.value).pipe(
delay(1000), // only affects "success"
catchError(error => interval(1000).pipe( // only affects "error"
mergeMap(() => throwError(error)) // re-throw error after our delay
)),
).subscribe(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
)
}

React Native IOS App crashes when no network conection

On the simulator it does not crash and Alerts the error, but in production it is crashes as soon as fetch request suppose to be made and it is impossible to reopen the app until network connection is back (I turn on/off airplane mode for the testing)
here are the snippets of my code
componentWillMount: function(){
NetInfo.isConnected.addEventListener('change',this.handleConnectivityChange)
NetInfo.isConnected.fetch().done((data) => {
this.setState({
isConnected: data
})
console.log('this.state.isConnected: ', this.state.isConnected);
})
},
handleConnectivityChange: function(){
var connected = this.state.isConnected ? false : true
this.setState({isConnected: connected})
console.log('this.state.isConnected11: ', this.state.isConnected);
},
....
goToList: function(replace, listview){
console.log('this.state.isConnected: ', this.props.isConnected);
if (!this.props.isConnected){
AlertIOS.alert('Error', 'Please check your network connectivity')
this.props.removeFetching()
return
}
....
fetch(url)
.then((response) => response.json())
.then((responseData) => {
....
.catch((error) => {
StatusBarIOS.setNetworkActivityIndicatorVisible(false)
AlertIOS.alert('Error', 'Please check your network connectivity')
this.props.removeFetching()
})
.done()
I spent a lot of time trying to find a way to catch exceptions when using fetch() but I was unable to get it working (e.g. using .catch() or a try/catch blog didn't work). What did work was to use XMLHttpRequest with a try/catch blog instead of fetch(). Here's an example I based off of: https://facebook.github.io/react-native/docs/network.html#using-other-networking-libraries
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('success', request.responseText);
var responseJson = JSON.parse(request.responseText);
// *use responseJson here*
} else {
console.warn('error');
}
};
try {
request.open('GET', 'https://www.example.org/api/something');
request.send();
} catch (error) {
console.error(error);
}

Handling INVALID_SESSION_TOKEN ERROR CODE 251 with React Native + Parse + Facebook

It seems as though the solution cited here:
Parse Facebook login fails with error code 251
No longer works. I have attempted both that and reconfiguring my Facebook app by resetting the secret, reconfiguring Parse with my new app credentials, and resetting xCode for a new simulator environment and all have failed. I continue to get old authentication data when the following function is called:
//sign up into parse db
Parse.FacebookUtils.logIn(authData, {
success: (user) => {
if (user.existed()) {
// login: nothing to do
console.log('User Already Logged In');
that.setState({loadingCurrentUser: false});
that.props.navigator.immediatelyResetRouteStack([{ name: 'home'}]);
} else {
// signup: update user data, e.g. email
console.log('getting user additional information');
var data = user.get('authData').facebook;
var api = 'https://graph.facebook.com/v2.3/'+data.id+'?fields=name,email&access_token='+data.access_token;
var fetchProfile = new FBSDKGraphRequest((error, result) => {
if (error) {
// TODO: error
this.setState({loadingCurrentUser: false});
} else {
console.log(result);
var name = responseData.name;
var email = responseData.email;
// FIXME: https://github.com/ParsePlatform/ParseReact/issues/45
var userId = {
className: '_User',
objectId: user.id
};
ParseReact.Mutation.Set(userId, {
username: email,
email: email,
name: name
}).dispatch();
that.setState({loadingCurrentUser: false});
that.props.navigator.immediatelyResetRouteStack([{ name: 'onboarding'}]);
}
}, '/me?fields=name,email');
// FIXME https://github.com/facebook/react-native-fbsdk/issues/20
// fetchProfile.start();
FBSDKGraphRequestManager.batchRequests([fetchProfile], function() {}, 10)
}
},
error: (user, error) => {
console.log('Error', error);
console.log(user.token);
switch (error.code) {
case Parse.Error.INVALID_SESSION_TOKEN:
Parse.User.logOut().then(() => {
this.onFacebookLogin(token);
});
break;
default:
// TODO: error
}
that.setState({loadingCurrentUser: false});
that.setState({errorMessage: error.message});
}
});
I am not sure how to proceed. Any help with error 251 and the most recent version of React Native (iOS)?

Resources