I am creating a react native app and doing the login and profile page. I have used the "async saveToStorage(userData)" for save the user data. Now i want to get the same data in the profile page.
I want to use this
getData = async () => {
try {
const value = await AsyncStorage.getItem('#storage_Key')
if(value !== null) {
// value previously stored
}
} catch(e) {
// error reading value
}
}
But how to use this in my profile page to Show this.
I saved this in the login page
async saveToStorage(userData){
if (userData) {
await AsyncStorage.setItem('user', JSON.stringify({
isLoggedIn: true,
authToken: userData.auth_token,
id: userData.user_id,
name: userData.user_login
})
);
return true;
}
return false;
}
And in the Profile page i have to display the name only. So how can use that.
import AsyncStorage from '#react-native-community/async-storage';
export default class Profile extends Component {
constructor(props){
super(props)
this.state={
userEmail:'',
userPassword:'',
}
}
var uservalue = await AsyncStorage.getItem('user');
home() {
Actions.home()
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}></View>
<Image style={styles.avatar} source={{uri: 'https://bootdey.com/img/Content/avatar/avatar6.png'}}/>
<View style={styles.body}>
<View style={styles.bodyContent}>
<Text style={styles.name}>Robert Vadra</Text>
<Text style={styles.info}>Total Token: 30 {uservalue.name}</Text>
<Text style={styles.description}>Lorem ipsum dolor sit amet, saepe sapientem eu nam. Qui ne assum electram expetendis, omittam deseruisse consequuntur ius an,</Text>
<TouchableOpacity style={styles.buttonContainer} onPress={this.home} >
<Text style={styles.buttonText}>Play Now</Text>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
In the place of "Robert Vadra", i want to display the stored value in it. Please help in this. Thanks in advance.
My Login page
export default class LoginForm extends Component<{}> {
constructor(props){
super(props)
this.state={
isLoggedIn:false,
userEmail:'',
userPassword:'',
}
}
login = () =>{
this.state.validating = true;
const {userEmail,userPassword} = this.state;
let reg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/ ;
if(userEmail==""){
this.setState({email:'Please enter Email address'})
}
else if(reg.test(userEmail) === false)
{
this.setState({email:'Email is Not Correct'})
return false;
}
else if(userPassword==""){
this.setState({email:'Please enter password'})
}
else{
fetch('http://mojse.com/wetest/userlogin.php',{
method:'post',
header:{
'Accept': 'application/json',
'Content-type': 'application/json'
},
body:JSON.stringify({
email: userEmail,
password: userPassword
})
})
.then((response) => response.json())
.then((responseJson)=>{
let data = responseJson.data;
if (this.saveToStorage(data)){
/* Redirect to home page */
Actions.profile()
} else {
alert("Wrong Login Details");
}
})
.catch((error)=>{
console.error(error);
});
}
Keyboard.dismiss();
}
render(){
return(
<View style={styles.container}>
<TextInput style={styles.inputBox}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Email"
placeholderTextColor = "#ffffff"
selectionColor="#fff"
keyboardType="email-address"
onChangeText={userEmail => this.setState({userEmail})}
/>
<TextInput style={styles.inputBox}
underlineColorAndroid='rgba(0,0,0,0)'
placeholder="Password"
secureTextEntry={true}
placeholderTextColor = "#ffffff"
ref={(input) => this.password = input}
onChangeText={userPassword => this.setState({userPassword})}
/>
<TouchableOpacity style={styles.button} onPress={this.login} >
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
</View>
)
}
async saveToStorage(userData){
if (userData) {
await AsyncStorage.setItem('user', JSON.stringify({
isLoggedIn: true,
authToken: this.state.authToken,
id: this.state.userid,
name: "KKKKKK"
})
);
return true;
}
return false;
}
}
You can get user data in the componentDidMount and save it to a state like this:
constructor(props){
super(props)
this.state={
userEmail:'',
userPassword:'',
userName:'',
}
}
componentDidMount() {
AsyncStorage.getItem('user').then((uservalue)=>{
uservalue = JSON.Parse(uservalue)
this.setState({userName: uservalue.name})
})
}
Now, you can use userName like this:
<Text style={styles.name}>{this.state.userName}</Text>
EDIT
First, please check that server response is correct ( maybe console.log(data) before save). Second, you are calling an async function so you have to wait until save function finish its work. also in save function, double check your data. my suggestion:
fetch('http://mojse.com/wetest/userlogin.php',{
method:'post',
header:{
'Accept': 'application/json',
'Content-type': 'application/json'
},
body:JSON.stringify({
email: userEmail,
password: userPassword
})
})
.then((response) => response.json())
.then(async (responseJson) => { // this is an async function
let data = responseJson.data;
console.log(data) // check and validate data correction
let res = await this.saveToStorage(data)
if (res){
/* Redirect to home page */
Actions.profile()
} else {
alert("Wrong Login Details");
}
})
.catch((error)=>{
console.error(error);
});
saveToStorage = async (userData) => {
if (userData) {
let model = { // full model with received data. this.state. authToken is not valid because we do not have a state called authToken.
isLoggedIn: true,
authToken: userData.authToken,
id: userData.userid,
name: userData.name
}
await AsyncStorage.setItem('user', JSON.stringify(model))
return true;
}
return false;
}
this is what i thik may be wrong and i did not test it. double check your code please.
I hope this can help you.
Related
I'm working on a React-Native project with REST APis, and I've currently got an invariant violation error. I've experienced this before, but I can't quite figure out what is causing it and how to fix it. If someone could point me in the right direction, I would really appreciate it! The full error is pictured below, and appears to be referencing a number of tags in the code, so I'm unsure exactly where it is originating. Thank you for reading, and thanks in advance!
The code is here:
import React, { Component } from 'react'
import { View, Text, Image, StyleSheet, FlatList} from 'react-native';
import * as Font from 'expo-font';
import styled from 'styled-components';
import dimensions from '../components/ScreenSize';
import colours from '../components/Colours';
import { Audio } from 'expo-av';
import { TouchableHighlight } from 'react-native-gesture-handler';
const client_id = {Client_ID}
const client_secret = {Client_Secret}
const item = ({item}) => (
<View style={{ flex:1, flexDirection: 'column', margin:1}}>
<TouchableHighlight onPress={() => this.fetchTracks(item.id)}>
<View>
<Text>{item.name}</Text>/>
</View>
</TouchableHighlight>
</View>
)
export default class HomeScreen extends React.Component {
state={
fontsLoaded:false,
}
async componentDidMount() {
await Font.loadAsync({
'montserrat-regular': require('../assets/fonts/Montserrat/Montserrat-Regular.ttf'),
'montserrat-light': require('../assets/fonts/Montserrat/Montserrat-Light.ttf'),
'montserrat-semibold': require('../assets/fonts/Montserrat/Montserrat-SemiBold.ttf'),
'montserrat-bold': require('../assets/fonts/Montserrat/Montserrat-Bold.ttf'),
}
).then(() => this.setState({ fontsLoaded:true }))
this.getToken();
this.setAudio();
}
constructor (props) {
super(props)
this.playbackInstance=null;
this.state = {
playing:false,
token: '',
DATA:[],
};
}
setAudio=() => {
Audio.setAudioModeAsync({
allowsRecordingIOS:false,
interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX,
playsInSilentModeIOS: true,
shouldDuckAndroid: true,
interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX,
playThroughEarpieceAndroid: false,
});
}
componentDidCatch(error, info)
{
console.log(error, info.componentStack);
}
getToken = async() =>
{
try
{
const getspotifytoken = await fetch("https://accounts.spotify.com/api/token",
{
method:'POST',
body: `grant_type=client_credentials&client_id=${client_id}&client_secret=${client_secret}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
const spotifytoken = await getspotifytoken.json();
this.setState({
token: spotifytoken.access_token
});
console.log(this.state.token);
}
catch(err)
{
console.log("Error fetching data", err);
}
}
search = async () => {
try
{
console.log("Searching: mood")
const spotifyApiCall = await fetch(`https://api.spotify.com/v1/browse/categories/mood/playlists?`, {
headers: {
Accept: 'application/json',
Authorization: `Bearer ${this.state.token}`,
"Content-Type":'application/json'
}
})
const spotify = await spotifyApiCall.json();
console.log("Items", spotify);
this.setState({
DATA: spotify.playlists.items,
})
}
catch (err)
{
console.log("Error fetching data", err);
}
}
fetchTracks = async (playlistId) => {
console.log('Playlist ', playlistId)
try
{
const getplaylist = await fetch(`https://api.spotify.com/v1.playlist/${playlistId}`,
{
method:'GET',
headers: {
Accept:"application/json",
Authorization:`Bearer ${this.state.token}`,
"Content-Type":"application/json"
}
});
const playlist = await getplaylist.json();
console.log('music ', playlist.tracks.items[0].preview_url);
}
catch (err)
{
console.log("Error fetching data ", err);
}
}
async _loadNewPlaybackInstance(playing, track) {
if(this.playbackInstance != null)
{
await this.playbackInstance.unloadAsync();
this.playbackInstance.setOnPlaybackStatusUpdate(null);
this.playbackInstance = null;
}
const source = {uri: track};
const initialStatus = {
shouldPlay: true,
rate: 1.0,
shouldCorrectPitch: true,
volume: 1.0,
isMuted: false
};
const {sound, status} = await Audio.Sound.createAsync(
source.initialStatus);
this.playbackInstance=sound;
this.playbackInstance.setIsLoopingAsync(false);
this.playbackInstance.playAsync();
if (this.state.selected === playlistId) {
console.log("Playing, so stop");
this.setState({selected:null});
this.playbackInstance.pauseAsync();
return;
}
this.setState({ selected:playlistId});
this._loadNewPlaybackInstance(true, playlist.tracks.items[0].preview_url);
}
render() {
if(!this.state.fontsLoaded ) {
return null
}
return (
<Container>
<Titlebar>
<Title>Music</Title>
</Titlebar>
<HeaderBar2>
<TouchableHighlight onPress={() => this.search()}>
<Header2>Playlists for your Mood</Header2>
</TouchableHighlight>
</HeaderBar2>
<View style={styles.MainContainer}>
{
this.state.DATA.length == 0 &&
<Text style={{padding:10, color:'#D3D3D3'}}/>
}
<FlatList
data = {this.state.DATA}
renderItem={item}
keyExtractor = {item.id}
numColumns={2}
extraData = {this.state}
/>
</View>
</Container>
);
}
}
I think u just have a little typo ..
check this line: <Text>{item.name}</Text>/>
change the last Text to </Text>
I am pretty new to react native. I am currently grabbing data from my node.js and trying to show all the data I grabbed into my View. In react.js, i did
documnet.getElementById.append().
What is the best way to do it in react native?
my code looks something like this
class GlobalRankings extends Component{
constructor(){
super();
this.state = {
}
this.getGlobalRankings();
}
getGlobalRankings(){
var request = new Request(checkEnvPort(process.env.NODE_ENV) + '/api/global_rankings', {
method: 'GET',
headers: new Headers({ 'Content-Type' : 'application/json', 'Accept': 'application/json' })
});
fetch(request).then((response) => {
response.json().then((data) => {
console.log(data);
for (var i in data.value){
console.log(data.value[i]); //where i grab my data
}
});
}).catch(function(err){
console.log(err);
})
}
render(){
return(
<View style={styles.container}>
// want my data to be here
</View>
)
}
}
Thanks for all the help
You can make an array in state in constructor, this.state = { arr: [] }
Then you assign the data array you get from the response.
fetch(request).then((response) => {
response.json().then((data) => {
this.setState({ arr: data.array });
});
}).catch(function(err){
console.log(err);
});
Then in the component body,
<View style={styles.container}>
{
this.state.arr.map((value, index) => {
return(
<Text key={index}>{value.text}</Text>
);
})
}
</View>
I understand that this.props.isValidUser gets updated after action dispatches the axios promise. if the user is not valid is shows message. If the user is valid user, I want to navigate to another screen to enter pin. How do I navigate to another screen after I get axios result from action?
types.js
export const VALIDATE_USER = "VALIDATE_USER";
export const VALIDATE_PIN = "VALIDATE_PIN";
export const GET_ERRORS = "GET_ERRORS";
Reducer.js
import { VALIDATE_USER, VALIDATE_PIN, GET_ERRORS } from "../actions/types.js";
export default function (state = initialState, action) {
switch (action.type) {
case VALIDATE_USER:
return {
...state,
isValidUser: (action.payload == true) ? true : false,
Id: action.employeeId
};
case VALIDATE_PIN:
return {
...state,
isValidPin: action.payload,
action: "VALIDATE_PIN",
};
default:
return state;
}
}
action.js
import { GET_ERRORS, VALIDATE_USER, VALIDATE_PIN, } from "./types";
export const validateUser = (empId) => dispatch => {
axios.get(`${API}/api/Account/ValidateMobileAppUser?employeeId=${empId}`)
.then(res => {
dispatch({
type: VALIDATE_USER,
payload: res.data,
Id: empId,
});
})
.catch(err => {
dispatch({
type: VALIDATE_USER,
payload: false,
Id: empId
});
});
};
Login.js
import PropTypes from "prop-types";
import { validateUser } from "../actions/authActions";
class Login extends PureComponent {
constructor() {
super();
this.state = {
employeeId: "",
pin: "",
isValidUser: false,
};
this.onValidateUser = this.onValidateUser.bind(this);
this.onEmployeeId = this.onEmployeeId.bind(this);
}
onEmployeeId(employeeId) {
this.setState({ employeeId });
}
onValidateUser() {
this.props.validateUser(this.state.employeeId);
}
render() {
const { loading } = this.props.loading;
return (
<KeyboardAvoidingView style={styles.login} >
<ScrollView showsVerticalScrollIndicator={false}>
<Block padding={[10, theme.sizes.base * 2]} onPress={Keyboard.dismiss}>
<Block middle>
<Input
placeholder={this.state.placeholder}
keyboardType={this.state.keyboardType}
style={[styles.input]}
value={this.state.employeeId}
onChangeText={this.onEmployeeId}
/>
{(this.props.isValidUser == false) ? (
<Text center style={{ color: "#C00000", marginTop: 15, fontSize: 14 }}>
Employee Id not registered. Please contact HR.
</Text>
) : ""}
<Button
gradient
style={styles.loginButton}
onPress={this.onValidateUser}
>
<Text white center>
Login
</Text>
</Button>
</Block>
<Button
onPress={() => this.onGoToStep(1)}
style={{
borderWidth: 1,
borderRadius: 30,
borderColor: "#E46932"
}}
>
<Text gray caption center style={{ color: "#E46932" }}>
Don't have an account? Sign Up
</Text>
</Button>
</Block>
</ScrollView>
</KeyboardAvoidingView>
);
}
}
Login.propTypes = {
validateUser: PropTypes.func.isRequired,
errors: PropTypes.object.isRequired
};
function reducerCallback(state, ownProps) {
if (state.auth.isValidUser == true) {
ownProps.navigation.navigate("mPin", { Id: state.auth.employeeId, type: "LOGIN" });
}
}
const mapStateToProps = (state, ownProps) => ({
auth: reducerCallback(state, ownProps),
isValidUser: state.auth.isValidUser,
errors: state.errors
});
export default connect(
mapStateToProps,
{
validateUser,
}
)(Login);
this.props.isValidUser == false tells me if the user is valid or not. But if the user is valid I'm navigating to another screen using reducerCallback() function. I'm not aware if this is the correct way to do so. My question is how to I navigate to another screen after I get return result from async axios action and How to I set local state using setState when I get callback from axios dispatch. Please guide
Try to below code:
login.js:
onValidateUser() {
this.props.validateUser({
empId: this.state.employeeId,
onSuccess: () => {
//Navigate to other screen
},
onFailure: () => {
//Alert error message
},
});
}
Action.js:
export const validateUser = ({empId, onSuccess, onFailure}) => dispatch => {
axios
.get(
`${API}/api/Account/ValidateMobileAppUser?employeeId=${empId}`
)
.then(res => {
dispatch({
type: VALIDATE_USER,
payload: res.data,
Id: empId,
});
onSuccess();
})
.catch(err => {
dispatch({
type: VALIDATE_USER,
payload: false,
Id: empId
});
onFailure()
});
};
I have a simple login screen that asks for an email and password.
Login Screen
If the "Sign In" button is pressed and both of the fields are blank I get this error: "null is not an object (evaluating'_this.state.Email')"
Error Screen
Here is the code:
import React, {Component} from 'react';
import {View, Button, ScrollView, AsyncStorage, Alert } from 'react-native';
import colors from '../config/colors';
import { TextInput } from '../components/TextInput';
class SignIn extends Component {
signIn = () => {
const {Email} = this.state;
const {Password} = this.state;
fetch('http://192.168.1.3/Restaurant_App/php/sign_in.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application.json',
},
body: JSON.stringify({
email: Email,
password: Password,
})
}).then((response) => response.json())
.then((responseJson) => {
if (responseJson == Email) {
Alert.alert(responseJson);
AsyncStorage.setItem('email', Email);
this.props.navigation.navigate('Search');
} else {
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
};
render() {
return (
<View>
<ScrollView style={{ backgroundColor: colors.background }}>
<TextInput
placeholder="Email..."
onChangeText={Email => this.setState({Email})}
/>
<TextInput
placeholder="Password..."
secureTextEntry={true}
onChangeText={Password => this.setState({Password})}
/>
</ScrollView>
<Button
onPress={() => this.signIn()}
title="Sign In"
/>
</View>
);
}
}
export default SignIn;
I would like it to be so that if the "Sign In" button is pressed with empty fields, I won't get this error. Instead, there should be an alert saying "Please fill in all fields." or something like that.
You should do some validation checks before making the fetch request.
You could do something like this
signIn = () => {
const {Email, Password} = this.state;
if(!this.checkDetails(Email, Password) {
// you could show an alert here, but it is not great UX,
// you should show your user where they have gone wrong,
// by making style changes, a red border around the TextInput,
// text explaining what has gone wrong.
return;
}
fetch('http://192.168.1.3/Restaurant_App/php/sign_in.php', {
...
}).then((response) => response.json())
.then((responseJson) => {
...
}).catch((error) => {
console.error(error);
});
};
checkDetails = (Email, Password) => {
// check that it is a valid email address
// this is a regex that I have used in the past to check email addresses.
const emailIsValid = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(Email);
// if the password has a minimum length then you should use that rather than 0
this.setState({emailIsValid, passwordIsValid: Password.length > 0});
if (emailIsValid && Password.length > 0) return true;
return false;
}
Using these new state values for the email and password being valid you could set additional styles and error text beside the fields that are wrong or missing.
<TextInput
placeholder="Email..."
onChangeText={Email => this.setState({Email})}
styles={this.state.emailIsValid ? styles.validEmail : styles.invalidEmail}
/>
{!this.state.emailIsValid && <Text>Please input a valid email</Text>}
<TextInput
placeholder="Password..."
secureTextEntry={true}
onChangeText={Password => this.setState({Password})}
styles={this.state.passwordIsValid ? styles.validPassword : styles.invalidPassword}
/>
{!this.state.passwordIsValid && <Text>Please input a valid password</Text>}
Don't for get to set up your styles for the different states.
const styles = StyleSheet.create({
validEmail: {},
validPassword: {},
invalidEmail: {},
invalidPassword: {}
});
You'll probably want to add initial state values for the emailIsValid and passwordIsValid so that they are set to true so that the correct styles are shown. Also you should define initial state for the Email and Password.
Add a constructor to your class
constructor (props) {
super(props);
this.state = {
Email: '',
Password: '',
emailIsValid: true,
passwordIsValid: true
}
}
I hope that this helps.
You can do at the top of your sign in function something like this:
If(this.state.email.length === 0 || this.state.password.length === 0) {
alert(“please complete the fields”);
return;}
I know was a thousand such questions relating to this same issue, but I've already exhausted ideas what might cause it in my case :/
I'm trying to update variable when after getting response from API.
I already changed all functions to use arrow function but I keep getting this error:
this.setState is not a function
and I can't find error in my code.
Can anyone see what's wrong?
app/routes/users/login/view.js
const UsersLoginView = (props) => {
let email = '';
this.state = {
textError: '',
inputError: false,
}
login = (event) => {
device_info = {
UUID: DeviceInfo.getUniqueID(),
brand: DeviceInfo.getBrand(),
model: DeviceInfo.getModel(),
system: DeviceInfo.getSystemName(),
system_version: DeviceInfo.getSystemVersion(),
timezone: DeviceInfo.getTimezone(),
locale: DeviceInfo.getDeviceLocale(),
}
fetch("my url", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
device: device_info
})
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
textError: 'SUCCESS',
inputError: false
});
})
.catch(error => {
this.setState({
textError: error.message,
inputError: true
});
})
.done();
},
updateEmail = (text) => {
email = text
}
return (
<Container>
<Content>
<Text style={{fontWeight: 'bold'}}>
User
</Text>
<Form>
<Item error={this.state.inputError}>
<Icon active name='ios-at-outline' />
<Input
autoCorrect={false}
placeholder='E-mail'
returnKeyType='go'
keyboardType='email-address'
autoCapitalize='none'
onChangeText = { (text) => updateEmail(text) }
/>
</Item>
<Text>{this.state.textError}</Text>
<Button full light style={{marginTop: 20}} onPress={ () => login }>
<Text>Login</Text>
</Button>
</Form>
</Content>
</Container>
);
};
export default UsersLoginView;
app/routes/users/login/index.js
import UsersLoginView from './view';
class UsersLogin extends Component {
constructor(props) {
super(props);
}
render() {
return (
<UsersLoginView />
);
}
}
export default UsersLogin;
maybe login function should be in index.js file then I will have access to state ?
The error is here: const UsersLoginView = (props) => {, you need to use a class if you want to maintain state.