I am trying to add Twilio Chat to my react native project. I'm getting an error with the name SyncError and code 0. I'm just trying to confirm it's connected at this point. Here's my basic setup.
Import at the top
import {Client as Chat} from 'twilio-chat'
Inside my class
componentDidMount = async () => {
console.log(Chat);
const token = await AsyncStorage.getItem('auth-token');
axios.get(config.apiUrl + '/chat/details', { headers: { Authorization: token } })
.then(res => {
console.log(res);
Chat.create(res.data.twilioToken)
.then(client => {
console.log('client', client);
this.subscribeToAllChatClientEvents(client);
})
.catch(error => {
console.log('There was an error', error);
});
})
.catch(err => {
console.log(err);
})
}
The error also mentions an "Unhandled promise rejection" but I've included any catch blocks where needed.
Thanks for any help.
For anyone getting the same issue. I realised that the problem was in my server code as I wasn't creating the twilio jwt token properly.
There's likely a problem with the token.
In my experience, I got a good token from my backend server and I save it on AsyncStorage. However, after a while the token wasn't working anymore.
I solved it by requesting the server a new twilio token each time I needed to instantiate the SDK client.
Related
i am new to react native i am trying to store the generated token from API to a storage so I can access it from anywhere in my application the generated token Is available in response.data.token i want to store it in something like session storage or local storage to access it from
axios({
method: 'POST',
url: 'http://127.0.0.1:8000/api/register',
data: Data,
})
.then(response => {
alert(JSON.stringify(response.data.token));
})
.catch(error => {
alert(JSON.stringify(error.response.data));
});
}
also pls let me know how i can check for if the token is stored in React Native debugger
You have to use #react-native-async-storage/async-storage library to store the token in LocalStorage.
After that use it like this.
import AsyncStorage from '#react-native-async-storage/async-storage';
axios({
method: 'POST',
url: 'http://127.0.0.1:8000/api/register',
data: Data,
})
.then(response => {
alert(JSON.stringify(response.data.token));
AsyncStorage.setItem('token', JSON.stringify(response.data.token));
})
.catch(error => {
alert(JSON.stringify(error.response.data));
});
}
Actually there is no exact way to check that token is available in the LocalStorage or not but you can console.log() it and check.
For checking it.
useEffect(() => {
const getUserToken = async () => {
const token = await AsyncStorage.getItem('token');
console.log("token",token)
};
getUserToken();
}, []);
You can use Redux to Store the Session Token
and with useSelector you can access token all over the app .
You can go through with these documentations
Link 1
Link 2
If you just want to save some data in an unsecured way and access it from anywhere, then yes, Async Storage is your option.
Just install the Async Storage like that:
yarn add #react-native-async-storage/async-storage
And then in any async function, you can call this to set data:
await AsyncStorage.setItem('your_data_identifier', data);
And call this to get data:
const data = await AsyncStorage.getItem('your_data_identifier');
More here https://react-native-async-storage.github.io/async-storage/
If you want a more secure way, there are a few libs, like this for example:
https://github.com/talut/rn-secure-storage
I am new to react native, I want to know how I can check the API POST and GET response as we checked the response of the API in networking in react js.
Right now I'm using expo to set up the project and the expo go app to work around
I am sending a POST req and it was showing an error
Possible Unhandled Promise Rejection (id: 0):
so I want to check the body what response I am sending to the API to fix the issue.
To send requests in react-native you use the javascript fetch function.
For example:
try {
const response = await fetch("www.yourapi.com", { method: "GET" });
let data = undefined;
if (response.status === 200) {
data = await response.json();
}
return data;
} catch (err: any) {
console.log(err)
}
I am working with vue and axios.
In one part of my project i am able to do post requests:
await axios.post(http://127.0.0.1:7000/favorite',body)
.then((response)=>
{
console.log(response.data)
}
)
.catch((error) =>
{
console.error(error)
})
But in another part in another file i am getting CORS error.
The code is almost the same:
await axios.post('http://127.0.0.1:7000/movie',body)
.then((response)=>
{
console.log("update ok")
}
).catch((error) =>
{
console.error(error)
})
and i see in my api terminal an OPTIONS request
The CORS settings in my api are right:
CORS_ORIFN_ALLOW_ALL = True
Also i can do successful post requests from postman.
I tried everything, what could be wrong?
I have started using Realm not long and I am trying to integrate a authentication workflow inside my RN app, using various tutorials, documentations. (I was using the nickname provider until now).
So at the moment, from the app, I can click on login, set my email/password and that user will be send to auth0.
But I can't manage to add that user into my Realm. And keep having that error:
"{"type":"https://docs.realm.io/server/troubleshoot/errors#invalid-credentials","title":"The provided credentials are invalid or the user does not exist.","status":401,"detail":"jwt malformed","code":611}"
Here is my Login function:
login = () => {
auth0.webAuth
.authorize({
scope: Config.AUTHO_SCOPE,
audience: Config.AUTH0_AUDIENCE,
device: DeviceInfo.getUniqueID(),
prompt: "login"
})
.then(res => {
console.log("res: ")
console.log(res)
auth0.auth
.userInfo({
token: res.accessToken
})
.then(data => {
//Error is here
const user = Realm.Sync.User.login(SERVER_URL, Realm.Sync.Credentials.jwt(res.accessToken))
this.onAuthenticated(data);
})
.catch(err => {
console.log("err: ");
console.log(JSON.stringify(err));
});
SInfo.setItem("accessToken", res.accessToken, {});
SInfo.setItem("refreshToken", res.refreshToken, {});
})
.catch(error => {
console.log("error occurrdzz");
console.log(error);
});
};
I am sure I am making mistakes, I think I didn't get all the steps to make an authentication works..
Anyway, thank you all for your help, I hope I've been precise enough !
I am using Expo to Login User with Facebook, I am receiving token with Graph Api but when I try to add the token in Async Storage it is not working.
Please see the code below:
async logIn() {
try {
const {
type,
token,
} = await Facebook.logInWithReadPermissionsAsync('<APP_ID>', {
permissions: ['public_profile'],
});
if (type === 'success') {
// Get the user's name using Facebook's Graph API
fetch(`https://graph.facebook.com/me?access_token=${token}`)
.then((res) => res.json())
.then((tokenKey) => AsyncStorage.setItem('userToken',tokenKey))
.then(() => this.props.navigation.navigate('App'))
} else {
// type === 'cancel'
}
} catch ({ message }) {
alert(`Facebook Login Error: ${message}`);
}
}
I am receiving the token when I console it
fetch(`https://graph.facebook.com/me?access_token=${token}`)
.then((res) => res.json())
.then((tokenKey) => console.log('userToken',tokenKey))
.then(() => this.props.navigation.navigate('App'))
Please help, I am new to react native and asynchronous programming in JavaScript. TIA :)
Try this if you want to get item from AsyncStorage
AsyncStorage.getItem('userToken', (error, result) => {
if (result) {
//result
}
else {
//error
}
});
Are you getting token from AsyncStorage with getItem?
AsyncStorage.getItem('userToken').then((token) => {
this.setState({hasToken: token !== null,localToken : token})
});
Sorry folks the problem was from my side, I was trying to store an object directly into Async Storage, whereas Async Storage only accepts values in String format. I used
.then((tokenKey) => AsyncStorage.setItem('userToken',JSON.stringify(tokenKey)))
and it fixed the problem,Thanks all for your help