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)
}
Related
I am creating a React Native in which i am sending my Form's data to Backend Node.js using Fetch and that worked all fine but i cannot execute anything down after fetch api, even console.log is not running.
React-Native Code:
const PostData = () =>{
console.log("Posting");
//Sending Request to Node.js using Fetch API
fetch("http://192.168.0.107:3000/Adminsignup", {
//Setting Method
method:"POST",
//Setting Headers
headers:{
//Setting Content-Type
"Content-Type" : "application/json"
},
//Stringifying the email and password and storing it into body
body:JSON.stringify({
name,
gmail,
password,
retype
})
}).then(res=>{
console.log(res);
}).catch(err=>{
console.log(err);
})
}
.then and .catch of fetch api is not working.
Ok so your front-end code is all good and as u said that your backend is also working when you fire PostData() function, check if you are returning the response from backend.
Add this in your signup Route:
res.status(200).send({result:"Successfully got Response"})
Catch status in your front-end like this:
let final = await fetch("http://192.168.0.107:5000/studentSignup", {
//Setting Method
method:"POST",
//Setting Headers
headers:{
//Setting Content-Type
"Content-Type" : "application/json"
},
//Stringifying the email and password and storing it into body
body:JSON.stringify({name,gmail,password,retype})
})
const data = final.status;
if(data === 200)
{
navigation.navigate("Your Route");
}
My app has a Firebase based Google login. I am trying to get access Token but getting undefined.I am getting the idToken but I need AccessToken and refresh Tokens.I need help
Here is my code :
GoogleSignin.configure({
scopes: ['profile', 'email','https://www.googleapis.com/auth/calendar'], //adding calender scope
webClientId: '863338747777-9bshdpj951ga8nik9tbtua52ji0h06k4.apps.googleusercontent.com',
offlineAccess: true,
forceCodeForRefreshToken: true,
});
const onGoogleButtonPress = async()=> {
try
{
await GoogleSignin.hasPlayServices();
const {accessToken, idToken} = await GoogleSignin.signIn();
const credential = auth.GoogleAuthProvider.credential(
idToken,
accessToken,
);
await auth().signInWithCredential(credential);
console.log('IDToken: ',idToken,accessToken)
console.log('AccessToken: ',accessToken)
}
catch(error)
{
console.log(error)
}
finally{
setLoggedIn(true)
}
}`
I found a solution for my own problem. I am using a older library of React native google sign in. The new one is react native login google. The new package is returning the accessToken as well. So to get the refresh token we need to use a api
This is the Link for that .
We need several headers
Take a look at them
You will get the serverAuthCode from the googleSignin function while signing in .
const UserInfo = await GoogleSignin.signIn();
Console log the UserInfo to get the serverAuthCode ,AccessToken and Refresh Token
This is the Package I am using for googlesignIn
Prabhakar I hope this link helpful for him.
https://www.freecodecamp.org/news/google-login-with-react-native-and-firebase/
Thank You
I'm using redux saga as middleware and call my request in this layer. When enable react-native debugger request works prefect, but without the debugger it seems request is not async anymore.
export function* userLoginSaga(action) {
yield put(actions.userLoginStart());
const response = yield GET(`${action.server}`, {
'Content-Type': 'application/json'
}, {
username: action.username,
password: action.password
});
if (response === 503) {
yield put(actions.serverErrorSuccess(response))
} else if (response.status === 200) {
yield put(actions.userLoginSuccess(response.data));
}
}
without react debugger, i get "undefined is not an object (response.status) ".
It's not waiting for response to get the result.
Please note that everything is working fine with debugger.
I have tried different ways with fetch or axios to POST to my server but it seems that the post body turns empty . My initial code is this.
So the connection to the server is good. I have configured server to respond with $_POST variables received but the $_POST return empty. This happens when I use JSON.stringify on body. I have also tried with FormData and it works fine but only on iOS. On my Android device and emulator I get Possible Unhandled Promise: Network request failed error (both https and http).
And I want to make it work on both iOS and Android. So till now I have manage to send post with formData only on iOS.
Any Solutions that works on Android and iOS?
import FormData from "FormData";
export const login = (emailUsername, password) => {
var formData = new FormData();
formData.append("emailUsername", emailUsername);
formData.append("password", password);
return async dispatch => {
const response = await fetch(
"https://myserver.net/api/app/auth.php",
{
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
emailUsername:emailUsername,
password:password
})
}
);
if (!response.ok) {
throw new Error("Something went wrong!");
}
const resData = await response.json();
console.log(resData);
};
};
Thanks to #bug I have find a solution. I was expecting to receive POST content to my $_POST or $_REQUEST variables on my server, but instead I had to get them this way.
$post_data = json_decode(file_get_contents('php://input'));
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.