How to make API Login Authentication in React-Native - react-native

I'm not exact sure how to make basic api login authentication with email and password. I'm stuck into here. If someone can help. That's my code:
class LoginScreen extends Component {
constructor(){
super();
this.state = {
email: '',
password: '',
result: false,
}
}
_userLogin() {
var email = this.state.username;
var password = this.state.password;
if (email && password) { // if validation fails, value will be null
fetch("https://URL/api/login", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: email,
password: password,
})
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
AlertIOS.alert(
"Login Success!"
),
this._onValueChange(STORAGE_KEY, responseData.id_token)
})
.done();
renderResults();
}
}
handleEmail = (text) => {
this.setState({ email: text })
}
handlePassword = (text) => {
this.setState({ password: text })
}
and then how to use it in the input fields and the button.

Related

Submit and redirect using POST method in form in ReactJs

I want to submit a sign up form from reactjs front-end to SQL via nodejs. GET method is working but POST method is not working.
Following is my code using POST:
form
<form action='/mainApp' method='POST' onSubmit={this.handleSubmit} id="signUpForm">
.
.
.
<button type="submit" className="btn btn-primary">
Sign Up
</button>
</form>
handleSubmit
handleSubmit = async (event) => {
event.preventDefault();
.
.
.
handdleData();
if (firstNameValidation && lastNameValidation && emailValidation && passwordValidation && confirmPasswordValidation && SQLValidation) {
document.getElementById("signUpForm").submit();
}
}
handleData
handleData = async (url) => {
const newData = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
id_: this.state.id,
firstName: this.state.firstName,
lastName: this.state.lastName,
email: this.state.email,
password: this.state.password,
}),
}).then(res => res.json());
console.log('newData-', newData);
return newData;
}
server.js
app.post('/mainApp/insert', async (req, res) => {
console.log('Insert called');
const result = await dbOperation.showVals('email', req.body.email);
console.log(result.rows.length);
if (result.rows.length > 0) {
console.warn('Duplicate email address');
res.send({ errorPresent: true, errorMessage: 'Duplicate email address' });
} else {
console.log('Inserting', req.body.id_, req.body.firstName, req.body.lastName, req.body.email, req.body.password);
await dbOperation.insertVals(req.body.id_, req.body.firstName, req.body.lastName, req.body.email, req.body.password);
res.send({ errorPresent: false, errorMessage: 'No error' });
}
});
I have done the same thing using GET method without the body and changing POST to GET and it works.

How to do React Native app once the user logs in, then it should be automatically logged in?

login request from API
How to do React Native app once the user logs in, then it should be automatically logged in?
Once logged into the application, it should automatically be able to log in every time.
export default class LoginForm extends Component {
state = {
email: "",
password: "",
login: false,
};
uri = Info.BaseUri + Info.LoginEndPoint;
# login request from API #
login = () => {
fetch(this.uri, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
identifier: this.state.email,
password: this.state.password,
}),
})
.then((response) => response.json())
.then((data) => {
if (data.user.email == this.state.email) {
saveUser(data.jwt, data.user);
this.props.navigation.navigate("Home");
}
})
.catch(() => {
alert("Email adresi veya parola hatalı!");
});
};

React Native: setState doesn't work when calling try-catch function

I tried to call APP with this code imported from another file and it worked fine:
import FormData from 'FormData';
import AsyncStorage from '#react-native-community/async-storage';
let formData = new FormData();
formData.append('userId', '1'); // < this is what I want to change
formData.append('key', '***'); //my key
export function getScoreFromAPI () {
return fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php',{
method : 'POST',
headers : {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body : formData
} )
.then((response) => {
return response.json()
})
.catch((error) => console.log("l'erreure est: " + error))
}
but now I want to change my userId from 1 to an constante from Asyncstorage, so I decide to change my code to this:
constructor(props) {
super(props)
this.state = { infos: [], userId: '' }
}
componentWillMount() {
this.getScoreFromAPI().then(data => {
this.setState({ infos: data })
});
console.log(this.state.infos);
AsyncStorage.getItem(USERID_STORED)
.then((data) => {
if (data) {
this.setState({userId:data})
}
});
}
async getScoreFromAPI() {
let formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //my key
try {
let response = await fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php',{
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
let res = await response.json();
} catch(error) {
console.warn("errors are " + error);
}
};
with a try-catch function but when I call getScoreFromAPI() in ComponentWillMount() I can't setState with received data, I still have an empty array in info:[]
my questions:
how can I replace '1' in userId by a value in asyncstorage in the first file ?
if it isn't possible, what I have do to setState info: [] with my data reveived
I've simplified your code into a promise chain in which calling getScoreFromAPI will execute after getting the userId from AsyncStorage, then storing the response into the infos state, while returning null if there was an error, and logging the error to the console. The data was not previously returned from getScoreFromAPI, so the value would always become null. I have not tested this code, but this should give you a good base to work from:
import FormData from 'FormData';
import AsyncStorage from '#react-native-community/async-storage';
export default class Test {
constructor() {
this.state = {
infos: null,
userId: ''
};
}
componentDidMount() {
AsyncStorage.getItem(this.state.userId)
.then(userID => {
this.setState({ userId: userID || '' });
})
.then(() => {
return this.getScoreFromAPI();
})
.then(data => {
this.setState({ infos: data });
})
.catch(console.error);
}
getScoreFromAPI = () => {
const formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //my key
fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(response => {
// use response data here
return response.json();
})
.catch(e => {
console.error(e);
return null;
});
};
}
You're doing your API call before fetching your value from AsyncStorage (I know this is async but it's not very readable if you do it that way).
getScoreFromAPI doesn't return anything, that's why your setState isn't working.
You don't need to use try and catch here, promises have their own error handling mechanism (the .catch() method).
I think callbacks are more readable and lead to less bugs than using .then() in code.
This is how I would do it:
constructor(props)
{
super(props);
this.state = { infos: [], userId: '' };
this.onSuccess = this.onSuccess.bind(this);
this.onFailure = this.onFailure.bind(this);
}
componentWillMount()
{
// Get userID from local storage, then call your API
AsyncStorage.getItem(YOUR_KEY)
.then(userID=> {
if (userID)
{
this.setState({ userId : userID }, () => {
this.getScoreFromAPI(this.onSuccess, this.onFailure);
});
}
});
}
onSuccess(data)
{
this.setState({
infos : data
});
}
onFailure(err)
{
console.warn('Error ' + err);
}
getScoreFromAPI(onSuccess, onFailure)
{
let formData = new FormData();
formData.append('userId', this.state.userId);
formData.append('key', '***'); //your key
fetch('https://www.globalfidelio.com/gfn_arcol/api/transaction.php', {
method : 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body: formData
})
.then(res => res.json())
.then(json => {
onSuccess(json);
})
.catch(err => {
onFailure(err);
});
}
It's finally done. I tried this and it worked. Thank you to all of you
this is what I have done:
...
const USERID_STORED = "userid_stored";
const GSM_STORED = "gsm_stored";
...
class ScoreList extends React.Component {
constructor(props) {
super(props)
this.state = { infos: [], userId: '', gsmStored: '', }
}
componentWillMount() {
AsyncStorage.getItem(USERID_STORED)
.then(userId => {
this.setState({ userId: userId});
this.getScoreFromAPI(this.state.userId).then(data => {
this.setState({ infos: data });
});
});
AsyncStorage.getItem(GSM_STORED)
.then(gsmStore => {
this.setState({ gsmStored: gsmStore});
});
}
getScoreFromAPI (userId) {
let formData = new FormData();
formData.append('userId', userId);
formData.append('key', '***');
return fetch('https://***',{
method : 'POST',
headers : {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data'
},
body : formData
} )
.then((response) => {
return response.json()
})
.catch((error) => console.log("l'erreure est: " + error))
};

how can we get post data from fetch function in react native to express api?

Question:
How can we get post data from fetch function in react native to express api?
Issue Faced:
I tried the following process but didn't got those variables in back-end API.
How can the variables be achieved in the backend API? Any suggestions are highly appreciated.
Here is the reactive native fetch function:
REACT NATIVE FETCH FUNCTION:
login = async () => {
await fetch('http://192.168.1.160:8001/api/login', {
method: 'POST',
mode: 'cors',
cache: 'default',
header: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password
})
})
.then ((response) => response.json())
.then ((res) => {//console.log(res);
if(res.error === false){
AsyncStorage.setItem('user', res.data);
this.props.navigation.navigate('profile');
} else{
// alert(res.message);
}
})
}
Express-API:
The express API is given below:
module.exports = function (req, res) {
console.log('TEST',req.body);
let { email, password } = req.body;
let input = { email, password };
const validator = loginValidator(input);
if (validator.error) {
return res.status(400).json({
error: true,
message: validator.error.details,
});
} else {
models.users.findOne({
where: { email: email }
}).then(user => {
if (!user) {
return res.status(400).json({
error: true,
message: {
key: 'email',
text: MessageHelper.email_already_exist
}
});
} else if (!bcrypt.compareSync(password, user.password)) {
return res.status(400).json({
error: true,
message: {
key: 'password',
text: MessageHelper.password_not_valid
}
});
} else {
var token = jwt.sign({ userid: user.id },Config.get('jwt.privatekey'));
models.users.update({ token: token },{ where: { id: user.id } }).then(function(result){
return res.json({
error: false,
message: MessageHelper.user_token_updated,
token: token,
data: {
user_id: user.id,
firstname: user.firstname,
lastname: user.lastname,
username:user.username,
email: user.email,
mobile: user.mobile,
token: user.token
}
});
}).catch(function(error){
return res.status(400).json({
error: true,
message: error
});
})
}
});
}
}
Fetch also takes an optional second argument that allows you to
customize the HTTP request. You may want to specify additional
headers, or make a POST request:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Networking is an inherently asynchronous operation. Fetch methods will
return a Promise that makes it straightforward to write code that
works in an asynchronous manner:
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}

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);
});