Cannot able to navigate to another screen in react native - react-native

I have made login authentication using POST API, I received success response, inside success response, I just want to navigate to other screen say for e.g(from Login screen to Videos screen).But it's not working for me pls look at my code and tell me where I made mistakes.
index.android.js:
export default class Registration extends Component {
render() {
const { navigation } =this.props;
return (
<Login navigation={ navigation }/>);
}
}
src/Login.js:
class Login extends Component {
constructor(props) {
super(props);
this.redirect=this.redirect.bind(this)
this.state = {
email: '',
password: '',
errors: '',
}
}
On button submit i just calling below method
CallSignIn() {
fetch("http://localhost:3000/users/login", { method: "POST", body: JSON.stringify({ email: this.state.email, password: this.state.password }), headers: { 'x-api-key': '7LH9ElCr4p1GLiMXAWLu0a9UsvKZ4wJr7t1N3ewh', 'Content-Type': 'application/json' } })
.then((response) => response.json())
.then((responseData) => {
this.setState({ showProgress: false })
this.redirect()
Alert.alert("success:", JSON.stringify(responseData.token));
})
.done();
}
redirect() {
const { navigate } = props.navigation;
navigate('Videos')
}
}

Related

Axios throws an "unauthorized" at me

This is strange because postman allows me to make a POST however react does not. the token is valid and when called, the token prints to console
export default class Create extends Component {
//url = 'http://127.0.0.1:5000/wtw/articles/'
constructor(props) {
super(props);
this.state = {
//author?
title: '',
description: '',
//image: ,
//token: null
};
}
handleCreate = async () => {
const { title, description, image } = this.state;
let token = await AsyncStorage.getItem('token');
axios
.post('http://127.0.0.1:5000/wtw/articles/', {
headers: {
Authorization: 'Token ' + token,
},
data: {
title: title,
description: description,
},
})
.then(async (Response) => {
console.log(Response);
})
.catch((err) => {
console.log();
console.log(err);
console.log(token);
});
};
}

React Native Logout Using Access Token Error

This is a simple app to login with API and logout. I retrieved Access Token when login. I navigated the access token to sidebar and trying to log out using logout function
SideBar.js
import React from 'react';
import { Text, Alert } from 'react-native';
import { Drawer,Container, Content, Header, Right, Button } from 'native-base';
export default class SideBar extends React.Component {
constructor(props) {
super(props)
this.state = {
token: this.props.usertoken
}
}
UserLogoutFunction = () =>{
const { token } = this.state;
fetch('https://api.idepoz.com/ncl/api/logout', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': `Bearer ${token}`,
},
body: JSON.stringify({
})
}).then((response) => response.json())
.then((responseJson) => {
console.log("token");
if(responseJson)
{
this.props.navigation.navigate('Login');
Alert.alert("Succesfully Logged Out");
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<Container>
<Header>
</Header>
<Content>
<Button transparent onPress={ this.UserLogoutFunction } >
<Text style={{fontSize: 24}}>Log Out</Text>
</Button>
</Content>
</Container>
);
}
}
It returning NETWORK REQUEST FAILED.
The below function returned access token while login
UserLoginFunction = () =>{
const { UserName } = this.state ;
const { UserPassword } = this.state ;
fetch('https://api.idepoz.com/ncl/api/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: UserName,
password: UserPassword
})
}).then((response) => response.json())
.then((responseJson) => {
if(responseJson)
{
this.props.navigation.navigate('QrScan',{usertoken:responseJson.token});
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
Please tell what's wrong with the "UserLogoutFunction"

How to pass fetched data from server to multiple screens out of stack navigator in react native using redux?

I have a login function that fetches the user info from mysql database. I want to send this data to different screens some of them are out of stack navigator. I was researching for a while and got to know that this could be done using redux, but i could not find a clear example on how to achieve that. Any suggestion on how to do that?
Here is my login function:
login = () => {
if (this.state.inputFieldsStatus == true)
{
// this.setState({passwordError:" Something went wrong! "})
fetch('http://ip_Adress/login', {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
})
})
.then((response) => response.json())
.then((res) => {
// alert(JSON.stringify(res.message));
if (res.success === true ) {
// AsyncStorage.setItem('user', res.user);
this.props.navigation.navigate('Home',
// {
// screen: 'Messages',
// params:
// {
// message: res.message,
// otherParam: 'anything you want here'
// }
// },
{
screen: 'Profile',
params:
{
message: res.message,
otherParam: 'anything you want here'
}
}
);
} else {
this.setState({passwordError: res.message })
// alert(res.message);
}
})
.done();
}
else
{
// alert(' Please fill in all fields! ');
this.setState({passwordError:" Please fill in all fields! "})
}
}

How to make API Login Authentication in 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.

Issue while trying to post / get an API on expo

I'm new to react-native and it's my first app.
I'm trying to develop my app and connect it to my API. I develop all my app with the navigator view on Expo and there is no problem, the connection is good and I can get or post everything.
Now that I'm trying to fetch it with expo on my Android or Apple, there is no response.
Here is my code for the authentication:
login.js
import { post } from '../request/post';
export const login = (mail, pass) => {
console.log(mail)
console.log(pass)
console.log("POST request for login");
return post('/api/login', {
email: mail,
password: pass,
mobile: true
});
};
post.js
import { API_URL } from '../url';
import { getStorageToken } from '../../utils/asyncStorage';
const getHeaders = async () => {
const token = await getStorageToken();
const headers = {
Accept: 'application/json',
'Content-Type': 'application/json'
};
if (token !== 'undefined' && token.length > 0) {
headers['auth'] = `${token}`;
}
return headers;
};
export const post = async (destination, body) => {
const headers = await getHeaders();
const result = await fetch(`${API_URL}${destination}`, {
method: 'POST',
headers,
body: JSON.stringify(body),
});
console.log(result);
if (result.ok) {
return await result.json();
}
throw { error: result.status };
};
loginPage.js
import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet, ScrollView, Image, TextInput, Linking } from 'react-native';
import { setStorageAfterConnection } from '../../utils/asyncStorage';
import { CheckBox, Icon } from 'react-native-elements';
import { login } from '../../api/auth/login';
export default class LogIn extends React.Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
errorMessage: ''
};
}
submit = () => {
login(this.state.email, this.state.password)
.then(async (res) => {
await setStorageAfterConnection(res);
this.props.navigation.navigate('Home');
})
.catch((res) => {
if (res && res.error) {
this.setState({ errorMessage: res.error});
}
this.setState({ errorMessage: "Erreur de connexion"});
});
};
render() {
return (
...............................................
);
}
}
I tried to debug it and it seems to not find the function post() because I don't have any network request. I do not know what's the correct way to do an "API" component so I think I probably made some mistakes but I didn't find what I'm missing.
I used Lan connection and my API isn't hosted on local.
Regards,
Try to add async-await to "login":
export const login = async (mail, pass) => { <---- 'async' ADDED
console.log(mail)
console.log(pass)
console.log("POST request for login");
return await post('/api/login', { <---- 'await' ADDED
email: mail,
password: pass,
mobile: true
});
};
I tried to put some debug on my code:
export const post = async (destination, body) => {
console.log("A");
const headers = await getHeaders();
console.log("B")
const result = await fetch(`${API_URL}${destination}`, {
method: 'POST',
headers,
body: JSON.stringify(body),
});
console.log(result);
if (result.ok) {
return await result.json();
}
throw { error: result.status };
};
And I get on the console:
email
password
POST request for login
A
So the problem seems to be on my await getHeaders()
EDIT: Problem was solved. It was because of the getHeaders that try to get the token and failed.