I'm trying to save my data locally with AsyncStorage but there seems to be an issue when I use getData
const storeData = async (value: string) => {
//storing data to local storage of the device
try {
await AsyncStorage.setItem("#storage_Key", value);
} catch (e) {}
};
const getData = async () => {
try {
const value = await AsyncStorage.getItem("#storage_Key");
if (value !== null) {
// value previously stored
}
} catch (e) {}
};
...
<View>
<TextInput
editable
value={value}
/>
{storeData(value)}
{getData()}
</View>
I thought I would have my value back but I got a blank page. Any idea of how to use AsyncStorage ? I used https://react-native-async-storage.github.io/async-storage/docs/usage/ .
Instead of calling storeData function in the return, you should bind your async storage function to the textinput component. Below is an example code on how to use it.
// AsyncStorage in React Native to Store Data in Session
// https://aboutreact.com/react-native-asyncstorage/
// import React in our code
import React, { useState } from 'react';
// import all the components we are going to use
import {
SafeAreaView,
StyleSheet,
View,
TextInput,
Text,
TouchableOpacity,
} from 'react-native';
// import AsyncStorage
import AsyncStorage from '#react-native-community/async-storage';
const App = () => {
// To get the value from the TextInput
const [textInputValue, setTextInputValue] = useState('');
// To set the value on Text
const [getValue, setGetValue] = useState('');
const saveValueFunction = () => {
//function to save the value in AsyncStorage
if (textInputValue) {
//To check the input not empty
AsyncStorage.setItem('any_key_here', textInputValue);
//Setting a data to a AsyncStorage with respect to a key
setTextInputValue('');
//Resetting the TextInput
alert('Data Saved');
//alert to confirm
} else {
alert('Please fill data');
//alert for the empty InputText
}
};
const getValueFunction = () => {
//function to get the value from AsyncStorage
AsyncStorage.getItem('any_key_here').then(
(value) =>
//AsyncStorage returns a promise so adding a callback to get the value
setGetValue(value)
//Setting the value in Text
);
};
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.container}>
<Text style={styles.titleText}>
AsyncStorage in React Native to Store Data in Session
</Text>
<TextInput
placeholder="Enter Some Text here"
value={textInputValue}
onChangeText={(data) => setTextInputValue(data)}
underlineColorAndroid="transparent"
style={styles.textInputStyle}
/>
<TouchableOpacity
onPress={saveValueFunction}
style={styles.buttonStyle}>
<Text style={styles.buttonTextStyle}> SAVE VALUE </Text>
</TouchableOpacity>
<TouchableOpacity onPress={getValueFunction} style={styles.buttonStyle}>
<Text style={styles.buttonTextStyle}> GET VALUE </Text>
</TouchableOpacity>
<Text style={styles.textStyle}> {getValue} </Text>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 10,
backgroundColor: 'white',
},
titleText: {
fontSize: 22,
fontWeight: 'bold',
textAlign: 'center',
paddingVertical: 20,
},
textStyle: {
padding: 10,
textAlign: 'center',
},
buttonStyle: {
fontSize: 16,
color: 'white',
backgroundColor: 'green',
padding: 5,
marginTop: 32,
minWidth: 250,
},
buttonTextStyle: {
padding: 5,
color: 'white',
textAlign: 'center',
},
textInputStyle: {
textAlign: 'center',
height: 40,
width: '100%',
borderWidth: 1,
borderColor: 'green',
},
});
export default App;
Related
I am new in React Native and I want to apply AsyncStorage in my project. I am doing a project where I can add Classroom in the flatlist, then in each Classroom, I can add Student names of each class using flatlist. Asyncstorage will be applied in both Classroom list and Student list.
My expectation is , I add classroom A , classroom B and classroom C , then when I pressed Clasroom A, I can add the name of students and when I go to classroom B , the name list is still empty waiting for me to fill the list.
My actual result is , after I add studentA , studentB , studentC in classroom A, when I go to classroom B, the 3 students in classroom A is still available in the list of classroom B.
So , how can I fix this to meet my requirement or it would be very helpful and much appreciated if you could provide a code with explanation. Thank you very much in advance
this is my code for the MainMenu.js where I need to add classroom :
import React, { useState , useEffect } from 'react';
import {
View,
Text,
TouchableOpacity,
FlatList,
Alert,
TextInput,
StyleSheet,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '#react-native-async-storage/async-storage';
import { useNavigation } from '#react-navigation/native';
import { CardStyleInterpolators } from '#react-navigation/stack';
export default function MainMenu(){
const [classroomInput, setClassroomInput] = useState('');
const [classroom, setClassroom] = useState([]);
const navigation = useNavigation();
useEffect(() => {
getClassroom();
}, []);
useEffect(() => {
saveClassroom(classroom);
}, [classroom]);
const saveClassroom = async (classroom) => {
try {
const stringifyClassroom = JSON.stringify(classroom);
await AsyncStorage.setItem('classroom', stringifyClassroom);
} catch (error) {
console.log(error);
}
};
const getClassroom = async () => {
try {
const classrooms = await AsyncStorage.getItem('classroom');
if (classrooms !== null) {
setClassroom(JSON.parse(classrooms));
}
} catch (error) {
console.log(error);
}
};
const addClassroom = () => {
if (classroomInput === ''){
Alert.alert('Error', 'Please input class');
} else {
const newClassroom = {
id: Math.random().toString(),
Classroom: classroomInput,
};
setClassroom([...classroom,newClassroom]);
setClassroomInput('');
}
};
const deleteClassroom = (classroomId) => {
const newClassrooms = classroom.filter(item => item.id !== classroomId);
setClassroom(newClassrooms);
};
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder={'Add Classrooms'}
value={classroomInput}
onChangeText={(text) => setClassroomInput(text)}
/>
<TouchableOpacity onPress={() => addClassroom()} style={styles.button}>
<Text>Add Classroom</Text>
</TouchableOpacity>
<FlatList
style={styles.flatlist}
data={classroom}
keyExtractor = { (item) => item.id.toString() }
renderItem={({ item }) => (
<TouchableOpacity onPress= {() => navigation.navigate('Classroom', item)} >
<View style={styles.listItem}>
<View>
<Text>
{item?.Classroom}
</Text>
</View>
<View >
<TouchableOpacity style={[styles.delete ]} onPress={() => deleteClassroom(item?.id)}>
<Icon name="remove" size={15} color={'#fff'} />
</TouchableOpacity>
</View>
</View>
</TouchableOpacity>
)}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
input: {
width: '70%',
borderBottomWidth: 1,
marginBottom: 20,
},
button: {
backgroundColor: 'lightblue',
padding: 10,
marginBottom: 10,
},
delete: {
backgroundColor: '#ff3333',
padding: 5,
color: '#fff',
borderWidth: 1,
borderColor: '#ff9999',
borderRadius: 5,
},
listItem: {
flexDirection: 'row',
justifyContent: 'space-between',
width: '70%',
alignItems: 'center',
},
});
and this is the Classroom.js where I will add the student list
import React, { useState , useEffect } from 'react';
import {
View,
Text,
TouchableOpacity,
FlatList,
Alert,
TextInput,
StyleSheet,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '#react-native-async-storage/async-storage';
import { useRoute } from '#react-navigation/core';
const Classroom = ( {navigation}) => {
const [studentInput, setStudentInput] = useState('');
const [student, setStudent] = useState([]);
const route = useRoute();
useEffect(() => {
getStudent();
}, []);
useEffect(() => {
saveStudent(student);
}, [student]);
const saveStudent = async (student) => {
try {
const stringifyStudent = JSON.stringify(student);
await AsyncStorage.setItem('student', stringifyStudent);
} catch (error) {
console.log(error);
}
};
const getStudent = async () => {
try {
const students = await AsyncStorage.getItem('student');
if (students !== null) {
setStudent(JSON.parse(students));
}
} catch (error) {
console.log(error);
}
};
const addStudent = () => {
if (studentInput === ''){
Alert.alert('Error', 'Please input student name');
} else {
const newStudent = {
id: Math.random().toString(),
Name: studentInput,
};
setStudent([...student,newStudent]);
setStudentInput('');
}
};
const deleteStudent = (studentId) => {
const newStudent = student.filter(item => item.id !== studentId);
setStudent(newStudent);
};
return (
<View styles={styles.container}>
<TouchableOpacity onPress={()=> navigation.goBack()} style={styles.button}>
<Text>Back</Text>
</TouchableOpacity>
<Text style={{fontWeight: 'bold', fontSize: 20}}>{route.params.Classroom}</Text>
<TextInput
style={styles.input}
placeholder={'Add Student Name'}
value={studentInput}
onChangeText={(text) => setStudentInput(text)}
/>
<TouchableOpacity onPress={()=> addStudent()} style={styles.button}>
<Text>Add Student</Text>
</TouchableOpacity>
<FlatList
style={styles.flatlist}
data={student}
keyExtractor = { (item) => item.id.toString() }
renderItem={({ item }) => (
<View style={styles.listItem}>
<View>
<Text style={[styles.classText , {fontSize: 18}]}>
{item?.Name}
</Text>
</View>
<View >
<TouchableOpacity style={[styles.delete ]} onPress={() => deleteStudent(item?.id)}>
<Icon name="remove" size={15} color={'#fff'} />
</TouchableOpacity>
</View>
</View>
)}
/>
</View>
);
};
export default Classroom;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
input: {
width: '70%',
borderBottomWidth: 1,
marginBottom: 20,
},
button: {
backgroundColor: 'lightblue',
padding: 10,
marginBottom: 10,
},
listItem: {
flexDirection: 'row',
justifyContent: 'space-between',
width: '70%',
alignItems: 'center',
},
delete: {
backgroundColor: '#ff3333',
padding: 5,
color: '#fff',
borderWidth: 1,
borderColor: '#ff9999',
borderRadius: 5,
},
});
Your problem is you are setting all the students with the same key student.
What you need to do instead is use the class name to set a dynamic key for your storage if your class names are unique otherwise you need to use something like uuid in order to create unique ids for your classes.
for example you can do this in your save student function
const saveStudent = async (student) => {
try {
const stringifyStudent = JSON.stringify(student);
await AsyncStorage.setItem(`class${class.name}:students`, stringifyStudent);
} catch (error) {
console.log(error);
}
};
and do this for your get student function
const getStudent = async () => {
try {
const students = await AsyncStorage.getItem(`class${class.name}:students`);
if (students !== null) {
setStudent(JSON.parse(students));
}
} catch (error) {
console.log(error);
}
};
Also try using uuid package instead of Math.random for your id creation. It's true that getting same numbers using Math.random is very unlikely but it is still possible but with uuid this is impossible.
I have generated QR Code manually by asking user to input value but what I'm trying is to generate QR Code random(Qr should be generated from number) without asking input from user so how can I generate random QR Code by pressing button only? I'm working on project that requires random QR Code every time when they open their mobile app.
Here is my code:
import React, { Component } from "react";
import {
StyleSheet,
View,
TextInput,
TouchableOpacity,
Text,
} from "react-native";
import QRCode from "react-native-qrcode-svg";
class QrGenerator extends Component {
constructor() {
super();
this.state = {
// Default Value of the TextInput
inputValue: "",
// Default value for the QR Code
valueForQRCode: "",
};
}
getTextInputValue = () => {
this.setState({
valueForQRCode: this.state.inputValue,
});
};
render() {
return (
<View style={styles.MainContainer}>
<QRCode
//Setting the value of QRCode
value={"ComputerGen" + this.state.valueForQRCode}
//Size of QRCode
size={250}
//Background Color of QRCode
bgColor="#000"
//Front Color of QRCode
fgColor="#fff"
getRef={(ref) => (this.svg = ref)}
onPress={() => {}}
/>
<TextInput // Input to get the value to set on QRCode
style={styles.TextInputStyle}
onChangeText={(text) => this.setState({ inputValue: text })}
underlineColorAndroid="transparent"
placeholder="Enter text to Generate QR Code"
/>
<TouchableOpacity
onPress={this.getTextInputValue}
activeOpacity={0.7}
style={styles.button}
>
<Text style={styles.TextStyle}> Generate QR Code </Text>
</TouchableOpacity>
</View>
);
}
}
export default QrGenerator;
const styles = StyleSheet.create({
MainContainer: {
flex: 1,
margin: 10,
alignItems: "center",
paddingTop: 40,
},
TextInputStyle: {
width: "100%",
height: 40,
marginTop: 20,
borderWidth: 1,
textAlign: "center",
},
button: {
width: "100%",
paddingTop: 8,
marginTop: 10,
paddingBottom: 8,
backgroundColor: "#F44336",
marginBottom: 20,
},
TextStyle: {
color: "#fff",
textAlign: "center",
fontSize: 18,
},
});
What you want to do is to make a random string "inputValue" if it is empty.
getTextInputValue = () => {
if (this.state.inputValue.length === 0) {
const randomInputValue = Math.random().toString(36).slice(2) + Math.random().toString(36).slice(2);
this.setState({
valueForQRCode: randomInputValue,
inputValue: randomInputValue,
});
} else {
this.setState({
valueForQRCode: this.state.inputValue,
});
}
};
I am looking for an autocomplete-text-input with the floating suggestion box.
Please suggest me any package name that can help to make the same component.
I tried to many packages but nothing helps, some are pushing the next fields, others do not support click away listener.
Answer: I Suggest One Solution:
Step 1:
npm install react-native-autocomplete-input --save
Step 2:
import React, {useState, useEffect} from 'react';
// Import all the components we are going to use
import {
SafeAreaView,
StyleSheet,
Text,
TouchableOpacity,
View,
} from 'react-native';
// Import Autocomplete component
import Autocomplete from 'react-native-autocomplete-input';
const App = () => {
// For Main Data
const [films, setFilms] = useState([]);
// For Filtered Data
const [filteredFilms, setFilteredFilms] = useState([]);
// For Selected Data
const [selectedValue, setSelectedValue] = useState({});
useEffect(() => {
fetch('https://aboutreact.herokuapp.com/getpost.php?offset=1')
.then((res) => res.json())
.then((json) => {
const {results: films} = json;
setFilms(films);
//setting the data in the films state
})
.catch((e) => {
alert(e);
});
}, []);
const findFilm = (query) => {
// Method called every time when we change the value of the input
if (query) {
// Making a case insensitive regular expression
const regex = new RegExp(`${query.trim()}`, 'i');
// Setting the filtered film array according the query
setFilteredFilms(
films.filter((film) => film.title.search(regex) >= 0)
);
} else {
// If the query is null then return blank
setFilteredFilms([]);
}
};
return (
<SafeAreaView style={{flex: 1}}>
<View style={styles.container}>
<Autocomplete
autoCapitalize="none"
autoCorrect={false}
containerStyle={styles.autocompleteContainer}
// Data to show in suggestion
data={filteredFilms}
// Default value if you want to set something in input
defaultValue={
JSON.stringify(selectedValue) === '{}' ?
'' :
selectedValue.title
}
// Onchange of the text changing the state of the query
// Which will trigger the findFilm method
// To show the suggestions
onChangeText={(text) => findFilm(text)}
placeholder="Enter the film title"
renderItem={({item}) => (
// For the suggestion view
<TouchableOpacity
onPress={() => {
setSelectedValue(item);
setFilteredFilms([]);
}}>
<Text style={styles.itemText}>
{item.title}
</Text>
</TouchableOpacity>
)}
/>
<View style={styles.descriptionContainer}>
{films.length > 0 ? (
<>
<Text style={styles.infoText}>
Selected Data
</Text>
<Text style={styles.infoText}>
{JSON.stringify(selectedValue)}
</Text>
</>
) : (
<Text style={styles.infoText}>
Enter The Film Title
</Text>
)}
</View>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
backgroundColor: '#F5FCFF',
flex: 1,
padding: 16,
marginTop: 40,
},
autocompleteContainer: {
backgroundColor: '#ffffff',
borderWidth: 0,
},
descriptionContainer: {
flex: 1,
justifyContent: 'center',
},
itemText: {
fontSize: 15,
paddingTop: 5,
paddingBottom: 5,
margin: 2,
},
infoText: {
textAlign: 'center',
fontSize: 16,
},
});
export default App;
Currently I want to setState of userId inside the constructor. The thing I want is to get the firebase.auth.currentUser.uid stored to the userId when Login is successful or handleLogin called.
I have a poor knowledge in Programming. So please ignore the other errors in the programs.
My code:
import React from 'react';
import { StyleSheet,
Text,
View,
TouchableOpacity,
AsyncStorage,
} from 'react-native';
import {RkTextInput, RkButton } from 'react-native-ui-kitten';
import {Actions} from 'react-native-router-flux';
import { createSwitchNavigator, createAppContainer } from 'react-navigation';
import Profile from "../Profile/Profile";
import SignUp from '../SignUp/SignUp';
import * as firebase from 'firebase';
export default class Login extends React.Component {
constructor(props){
super(props)
this.state=({
email:'savadks1919#gmail.com',
password:'123123',
userId:'',
errorMessage: null
})
}
componentDidMount() {
this._loadInitialState().done();
}
_loadInitialState = async () => {
let value= await AsyncStorage.getItem(this.state.userId)
}
signup() {
Actions.signup()
}
Home() {
Actions.home()
}
handleLogin = (email, password, userId) => {
firebase.auth().signInWithEmailAndPassword(email, password).then(
this.setstate ({
userId: firebase.auth().currentUser.uid
}),
alert(this.state.userId)
).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.titleText}>Taams</Text>
<Text style={styles.edition}>Developer's Edition</Text>
<Text style={styles.titleText}>Login.js</Text>
<Text>Alpha 0.0.0.1</Text>
{/*-----UserName Input-------*/}
<RkTextInput
rkType= 'rounded'
labelStyle= {{color: 'black', fontWeight: 'bold'}}
placeholder='UserName'
//--------------value Handler----------------//
onChangeText={(email) => this.setState({email})}
//---------------------------------//
selectionColor="#000000"
keyboardType="email-address"
onSubmitEditing={() => { this.password.focusInput(); }}
inputStyle={{
color: 'black',
fontWeight: 'bold',
}}/>
{/*-----Password-------*/}
<RkTextInput
secureTextEntry={true}
rkType= 'rounded'
placeholder='Password'
//--------------value Handler----------------//
onChangeText={(password) => this.setState({password})}
//---------------------------------//
ref={(input) => { this.password = input; }}
inputStyle={{
color: 'black',
fontWeight: 'bold',
}}/>
<RkButton onPress = {()=>this.handleLogin(this.state.email,this.state.password)}>
<Text style={styles.LoginButtonText}>Login</Text>
</RkButton>
<View style={styles.signupTextCont}>
<Text style={styles.signupText}>Don't have an account yet?</Text>
<TouchableOpacity onPress={this.signup}><Text style={styles.signinButton}>SignUp</Text></TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
signupTextCont:{
flexGrow: 0,
alignItems:'center',
justifyContent:'flex-end',
marginVertical:15
},
signupText:{
color:'rgba(64,64,64,0.6)',
fontSize:16
},
signinButton:{
color:'#000000',
fontSize:16,
fontWeight:'500'
},
titleText: {
fontSize: 20,
fontWeight: 'bold',
},
edition: {
fontSize: 15,
//fontWeight: 'bold',
},
TextInput: {
width: 300,
height:50,
borderColor: 'grey',
borderWidth: 1,
},
LoginButtonText: {
fontSize: 20,
fontWeight: 'bold',
color: 'white',
//alignItems: 'center'
},
});
If you are coming from different screen with navigation on login screen then you need to pass userId in Params of react-navigation like this
this.props.navigation.navigate('Login', params)
and get these params in your constructor like this to get the userId
this.props.navigation.getParams('params')
if you are on the login screen and calling your auth function for authentication of user and also you need this Data in your component then you need to setState on the response of your auth function
setState({userData: res})
Or you can do initialisation inside constructor
this.state={ userId: firebase.auth.currentUser.uid }
I am using below versions
react-native-router-flux ^3.39.1
react-native 0.44.0
I expecting that will call API which I am using with "fetch"
Have used componentDidMount but it's showing another error
undefined is not an object (evaluating 'this._component.getScrollableNode')
But I am getting below error outputs
Steps to reproduce
Create three scene using router flux (In my case App, Login, Home)
Use ScrollView for creating the Login.js Create a button
using TouchableHighlight after that call the fetch with a function
using onPress like onPress={ () => this.fetchData() }
Below code, I am using for App.js
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
AsyncStorage,
} from 'react-native';
import Login from './components/Login'
import Register from './components/Register'
import Home from './components/Home'
import { Scene, Router, TabBar, Modal, Schema, Actions, Reducer, ActionConst } from 'react-native-router-flux'
const reducerCreate = params=>{
const defaultReducer = Reducer(params);
return (state, action)=>{
console.log("ACTION:", action);
return defaultReducer(state, action);
}
};
export default class App extends Component {
constructor(props, context) {
super(props, context);
this.state = {
logged: false,
loading: true,
};
};
componentWillMount(){
self = this;
AsyncStorage.getItem('token')
.then( (value) =>{
if (value != null){
this.setState({
logged: true,
loading: false,
});
}
else {
this.setState({
loading: false,
})
}
});
};
render() {
if (this.state.loading) {
return <View><Text>Loading</Text></View>;
}
return (
<Router>
<Scene hideNavBar={true} key="root">
<Scene key="logIn" component={Login} title="Login" initial={!this.state.logged}/>
<Scene key="regisTer" component={Register} title="Register"/>
<Scene key="home" component={Home} title="home" initial={this.state.logged}/>
</Scene>
</Router>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
And below code, using for Login.js
/* #flow */
import React, { Component } from 'react';
import {
View,
StyleSheet,
Image,
ScrollView,
TextInput,
Text,
TouchableHighlight,
Alert,
} from 'react-native';
import { Container, Content, InputGroup, Input, Icon, Item } from 'native-base';
import Button from 'react-native-button'
import {Actions} from 'react-native-router-flux'
import ResponsiveImage from 'react-native-responsive-image'
export default class Login extends Component {
constructor(props){
super(props)
this.state = {
email: '',
password: '',
data: '',
}
}
fetchData() {
fetch('http://allstariq.tbltechnerds.com/api/login/?username=andress&password=23434')
.then((response) => response.json())
.then((responseData) => {
this.setState({
data: responseData.movies,
});
})
.done();
}
render() {
return (
<View style={styles.container}>
<ScrollView>
<View style={ styles.logoContainer }>
<View style={{flexDirection: 'row',}}>
<ResponsiveImage
source={require('../assets/logo.png')}
initWidth="300"
initHeight="160" />
</View>
</View>
<View style={ styles.formContainer }>
<Item>
<Icon active name='mail' />
<Input
onChangeText={(text) => this.setState({email: text})}
value={this.state.email}
placeholder='Email'/>
</Item>
<Item>
<Icon active name='key' />
<Input
onChangeText={(text) => this.setState({password: text})}
value={this.state.password}
placeholder='Password'/>
</Item>
<TouchableHighlight
style={ styles.loginButton }
onPress={ () => this.fetchData() }>
<Text style={ styles.btnText}>Login</Text>
</TouchableHighlight>
</View>
<View style={ styles.bottomContainer }>
<Text style={ styles.cenText }>Dont worry if you haven't an account yet . . </Text>
<Text
style={ styles.blueText}
onPress={ Actions.regisTer }
>Register Now</Text>
</View>
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
logoContainer: {
flex: .5,
padding: 10,
justifyContent: 'center',
alignItems: 'center',
},
logoItem: {
width: null,
height: null,
resizeMode: 'cover',
},
formContainer: {
flex: 4,
padding: 10,
},
inputelm: {
marginBottom: 10,
backgroundColor: '#999',
borderWidth: 0,
fontSize: 20,
color: '#FFF',
fontFamily: 'AmaticSC-Bold',
},
loginButton: {
borderRadius: 3,
marginBottom: 20,
marginTop: 20,
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#2196f3',
elevation: 4,
},
signupButton: {
borderRadius: 3,
marginBottom: 20,
marginTop: 20,
paddingLeft: 10,
paddingRight: 10,
backgroundColor: '#7cb342',
elevation: 4,
},
btnText: {
textAlign: 'center',
color: '#FFF',
fontSize: 30,
lineHeight: 40,
},
blueText: {
textAlign: 'center',
color: '#2196f3',
fontSize: 20,
lineHeight: 40,
},
bottomContainer: {
flex: 1,
padding: 10,
},
cenText: {
textAlign: 'center',
fontSize: 16,
},
});
What is the actual way to use fetch with react-native-router-flux? I am new to react, please help me.
well, its a couple of months late but the problem here is that your fetchData method hasn't got access to this because when you declare a method like this:
fetchData() {
}
Under the hood react is creating a function this way:
this.fetchData = function() {
}
when you declare a function using the function keyword, everything between {} will have its own "this" and your method will not have access to the "this" of the component context.
That is the reason why you are getting the "undefined", because you are calling "this.setState" inside the promise returned by fetch, so the error is not fetch, but this.
To solve this issue you could just define your method this way:
fetchData = () => {
}
And because the functions defined with a fat arrow do not create their own scope, the component "this" will be available from inside your method.
Did you try maybe to import the library?
Import fetch from "fetch";
You have not imported the fetch function, import it from the node-fetch module like
import fetch from 'node-fetch'