How to pass link parameter from react native fetch method to express js server - react-native

I'm trying to pass the link parameter to express js server, so how can i pass through fetch method in react native ?
here is my lines of code to fetch the particular
searchByID = () => {
this.setState({ ActivityIndicator_Loading: true }, () => {
const {ticket} = this.state.ticketid;
fetch('http://192.168.0.108:3000/users/${ticket}',
{
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((res) => {
if (res.success === true) {
alert(res.message);
this.setState({ dataSource: res.message })
AsyncStorage.setItem('userinfo', res);
this.setState({ ActivityIndicator_Loading: false });
}
else {
alert(res.message);
}
this.setState({ ActivityIndicator_Loading: false })
}).done();
})
}

Use the body field.
searchByID = () => {
this.setState({ ActivityIndicator_Loading: true }, () => {
const { ticket } = this.state.ticketid;
fetch('http://192.168.0.108:3000/users/${ticket}',
{
method: 'POST',
headers:
{
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ a: 1, b: 2 })
})
.then((response) => response.json())
.then((res) => {
if (res.success === true) {
alert(res.message);
this.setState({ dataSource: res.message })
AsyncStorage.setItem('userinfo', res);
this.setState({ ActivityIndicator_Loading: false });
}
else {
alert(res.message);
}
this.setState({ ActivityIndicator_Loading: false })
}).done();
})
}

Related

Await is only allowed within async functions error react native

I am new to react native and trying to save user obejct in application storage using await AsyncStorage.setItem('user', res[1].data); However I am getting error as
handleLogin = async() => {
NetInfo.fetch().then(state => {
if (state.isConnected) {
const {navigate} = this.props.navigation;
const data = {
email: this.state.userName,
password: this.state.password
};
fetch(`${DOMAIN_URL}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
.then((response) => {
const statusCode = response.status.toString();
const data = response.json();
return Promise.all([statusCode, data]);
})
.then((res) => {
if (res[0] == 200) {
await AsyncStorage.setItem('user', res[1].data);
navigate('Home');
}else{
Alert.alert(
res[1].message
);
}
})
.catch((error) => {
console.error(error);
});
}
else {
Alert.alert(
"No Internet!",
"Needs to connect to the internet in order to work. Please connect tablet to wifi and try again.",
[
{
text: "OK",
onPress: () => { }
}
]
);
};
})
};
I have made the handleLogin async but it doesn't solve the error. What is the correct way to store user obejct?
It is recommended that you use react-native-easy-app , through which you can access any data in AsyncStorage synchronously.
Sample_Hooks
StorageController
navigateToHome = async (user) => {
const { navigate } = this.props.navigation;
await AsyncStorage.setItem('user', user);
navigate('Home');
}
handleLogin = async() => {
NetInfo.fetch().then(state => {
if (state.isConnected) {
const data = {
email: this.state.userName,
password: this.state.password
};
fetch(`${DOMAIN_URL}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data)
})
.then((response) => {
const statusCode = response.status.toString();
const data = response.json();
return Promise.all([statusCode, data]);
})
.then((res) => {
if (res[0] == 200) {
navigateToHome(res[1].data);
}else{
Alert.alert(
res[1].message
);
}
})
.catch((error) => {
console.error(error);
});
}
else {
Alert.alert(
"No Internet!",
"Needs to connect to the internet in order to work. Please connect tablet to wifi and try again.",
[
{
text: "OK",
onPress: () => { }
}
]
);
};
})
};

Fetch virtual payment address of users in my react native app

I have integrated react-native-upi-payment in my app. The RNUpiPayment Component calls initializePayment method here which gives only vpa for a default user. How can I give vpa address for many users in my database by fecth api or any other methods? Any methods or suggestions please.
My code is here
<TouchableOpacity
style={styles.payBtn}
activeOpacity={0.5}
onPress={() => {
RNUpiPayment.initializePayment(
{
vpa: '8856452125#ybl', // or can be john#ybl or mobileNo#upi
payeeName: 'Stanlee',
amount: '20',
transactionRef: 'aasf-332-aoei-fn',
},
() => {
console.log('Success');
},
() => {
console.log('Failed');
},
);
}}>
<Text style={styles.payBtnTxt}>PAY</Text>
</TouchableOpacity>
Finally got it!
DriverPaymentFunction = () => {
const {DriverUPI} = this.state;
const {DriverName} = this.state;
fetch('http://ip/appname/payment.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
upi_id: DriverUPI,
driver: DriverName,
}),
})
.then((response) => response.json())
.then((responseJson) => {
// If server response message same as Data Matched
if (responseJson === 'Data Matched') {
RNUpiPayment.initializePayment( //Payment API
{
vpa: DriverUPI, // or can be john#ybl or mobileNo#upi
payeeName: DriverName,
amount: '0',
transactionRef: 'AppName Ride Transaction',
},
() => {
console.log('Success');
},
() => {
console.log('Failed');
},
);
} else {
Alert.alert(responseJson);
}
})
.catch((error) => {
console.error(error);
});
};

undefined response from axios.post

when i try to make a post request i get a network error, with an error.message of 'undefined'
here's the setup:
export default axios.create({
baseURL: API_HOST,
withCredentials: true,
crossdomain: true,
});
and the actual call:
export const Login = (email, password) => dispatch => {
axios
.post('/v1/login?', {email, password})
.then(response => {
console.log('yes');
token = () => {
return response.token ? response.token : '';
};
dispatch({
type: UPDATE_AUTH_PROPS,
payload: [
{prop: 'errorMessage', value: 'successed'},
{prop: 'token', value: token},
],
});
})
.catch(error => {
debugger;
dispatch({
type: UPDATE_AUTH_PROPS,
payload: [{prop: 'errorMessage', value: error.message}],
});
});
};
Try this, this is easy and readable...
axios
.post(api_url + '/v1/login?', data, {
'Content-Type': 'application/json',
})
.then(
res => {
alert('Response');
},
error => {
alert('Error');
},
);
}
};

How to get Html code by fetching web API response?

When we are trying to fetch html code via fetch API response but we are enable to get it because it return "Unexpected Token <"
onLoginService2 = async () => {
try {
var hittingURl = "https://members.iracing.com/membersite/Login?username=dave#rms55.com.au&password=rms55Pa55&utcoffset=-600&todaysdate=1558055491688&checkbox=0";
const myRequest = new Request(hittingURl.toString(),
{
method: 'POST',
headers: {
'Accept': 'text/html',
'Content-Type': 'text/html;charset=ISO-8859-1',
},
timeout: 1000,
// body: JSON.stringify("")
}
);
fetch(myRequest)
.then((response) => console.log("abcdefghijklmon--> "+JSON.stringify(response)))
.then((data) => {
console.log("RESPONSERR----> ",data+"");
// this.setState({ isLoading: false })
// this.onLoginSuccessFull(responseJson)
})
.catch((error) => {
this.setState({ isLoading: false })
console.log("response--31" + error);
})
} catch{
}
// }
}
The response of first then has a method .text(), which return Promise
Try this
fetch(myRequest)
.then(resp => resp.text())
.then(text => {
//text is html
})
*Just copy the above and run in console to see the result.

AsyncStorage not storing an item in react native after http success response

I have just tried to store an item in AsyncStorage after success
response.I have made http request using axios.I have little bit confused i tried already how to store data using AsyncStorage but when i trying to store an item on http request onSucess() is not storing.please help me where i made mistakes.
axios.post(url, { email: this.state.email, password: this.state.password } , config)
.then(function (response){
// Alert.alert("success:",JSON.stringify(response.data.token));
this.setState({ showProgress: false })
this.setState({token:JSON.stringify(response.data.token)});
var accesstoken=JSON.stringify(response.data.token);
console.log(accesstoken);
AsyncStorage.setItem("accesstoken",accesstoken);
Alert.alert("success:", accesstoken);
// Alert.alert("success:", JSON.stringify(accesstoken));
}).catch(function (error) {
Alert.alert("Error:",error);
});
Use below fetch method
fetch(url, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ email: this.state.email, password: this.state.password})
}).then((response) => response.json())
.then((responseData) => {
// Alert.alert("success:",JSON.stringify(response.data.token));
this.setState({ showProgress: false })
this.setState({token:JSON.stringify(response.data.token)});
var accesstoken=this.state.token;
console.log(accesstoken);
AsyncStorage.setItem("accesstoken",accesstoken);
}).catch((error) => {
Toast.show("There is a Problem on your network connection");
});
Here is the example use that :
`fetch(<hostURL>, {
method: 'POST',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',},
body: JSON.stringify({ email: <email> ,password: <password>})
}).then((response) => response.json())
.then((responseData) => {
if(responseData.STATUS == true){
AsyncStorage.multiSet([
["state", JSON.stringify(responseData.DATA[0])],
["country", JSON.stringify(responseData.DATA[1])]
]);
}
});`
Try this
axios.post(url, { email: this.state.email, password: this.state.password } , config)
.then(response => {
// Alert.alert("success:",JSON.stringify(response.data.token));
this.setState({ showProgress: false })
this.setState({token:JSON.stringify(response.data.token)});
var accesstoken=this.state.token;
console.log(accesstoken);
// Alert.alert("success:", JSON.stringify(accesstoken));
}).catch(error => {
Alert.alert("Error:",error);
});