Undefined is not an object (evaluating '_this2.setState') - react-native

I'm new on react-native development and i try to add a login / register to my application, my login by email and by facebook is working fine (i'm in Firebase database, so it's ok). I want to show another view after the login of the user. Here is my firebaseconfig (imported in my login) :
export async function loginUser(email, password) {
try {
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(response => {
this.setState({ authentificated: true });
});
} catch (error) {
console.log(error.toString);
}
}
export async function facebookLogin() {
Facebook.initializeAsync("928193664206969");
const { type, token } = await Facebook.logInWithReadPermissionsAsync(
"928193664206969",
{
permissions: ["public_profile"]
}
);
if (type == "success") {
const credential = firebase.auth.FacebookAuthProvider.credential(token);
firebase
.auth()
.signInWithCredential(credential)
.then(response => {
this.setState({ authentificated: true });
})
.catch(error => {
console.log(error);
});
}
}
Here is my Login page :
import React from "react";
import { View, Text } from "react-native";
import EmailLoging from "../components/EmailLoging";
import { Welcome } from "../pages/Welcome";
export default class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
authentificated: false
};
}
renderCurrentState() {
if (this.state.authentificated) {
return <Welcome />;
} else {
return <EmailLoging />;
}
}
render() {
return this.renderCurrentState();
}
}
In the application, when i click on login with facebook, it's work, then i go back to the login screen with this error :
undefined is not an object (evaluating '_this2.setState')
- node_modules\#firebase\auth\dist\auth.js:16:1054 in cb.prototype.toString
- node_modules\#firebase\auth\dist\auth.js:19:232 in <anonymous>
- node_modules\#firebase\auth\dist\auth.js:19:167 in xb
- node_modules\#firebase\auth\dist\auth.js:19:0 in wb
- node_modules\#firebase\auth\dist\auth.js:13:280 in <anonymous>
- node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
- node_modules\promise\setimmediate\core.js:123:25 in setImmediate$argument_0
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:146:14 in _callTimer
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:194:17 in _callImmediatesPass
- node_modules\react-native\Libraries\Core\Timers\JSTimers.js:458:30 in callImmediates
* [native code]:null in callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:407:6 in __callImmediates
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:143:6 in __guard$argument_0
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:384:10 in __guard
- node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:142:17 in __guard$argument_0
* [native code]:null in flushedQueue
* [native code]:null in invokeCallbackAndReturnFlushedQueue
I have done some search on Stackoverflow, and i found this : TypeError: undefined is not an object (evaluating 'this.setState') but i have only arrow function so it's not the problem..
Thank you
Update :
Now i don't have the error, but the screen didn't change after the login, my code, login functions : (firebaseConfig.js)
export async function loginUser(email, password) {
try {
firebase.auth().signInWithEmailAndPassword(email, password);
} catch (error) {
console.log(error.toString);
}
}
export async function facebookLogin() {
Facebook.initializeAsync("928193664206969");
const { type, token } = await Facebook.logInWithReadPermissionsAsync(
"928193664206969",
{
permissions: ["public_profile"]
}
);
if (type == "success") {
const credential = firebase.auth.FacebookAuthProvider.credential(token);
firebase
.auth()
.signInWithCredential(credential)
.catch(error => {
console.log(error);
});
}
}
Login.js :
import React from "react";
import { View, Text } from "react-native";
import Welcome from "../pages/Welcome";
import Home from "../pages/Home";
export default class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
authentificated: false
};
this.renderCurrentState = this.renderCurrentState.bind(this);
}
renderCurrentState = () => {
if (this.state.authentificated) {
return <Home />;
} else {
return <Welcome />;
}
};
render() {
return this.renderCurrentState();
}
}
Welcome.js :
import React from "react";
import { StyleSheet, Text, Image } from "react-native";
import { LinearGradient } from "expo-linear-gradient";
import logo from "../../assets/icon.png";
import { Button, Icon, Container } from "native-base";
import { Actions } from "react-native-router-flux";
import { facebookLogin } from "../components/firebaseConfig";
export default class Welcome extends React.Component {
render() {
return (
<LinearGradient
colors={["#004aaf", "#000"]}
style={{ flex: 1, alignItems: "center", justifyContent: "center" }}
>
<Container style={styles.backgroundImage}>
<Image source={logo} style={styles.logo}></Image>
<Text style={styles.loginText}>
─── Se connecter / S'inscrire avec ───
</Text>
<Button
light
full
rounded
style={{ padding: 10 }}
onPress={() => Actions.login()}
>
<Icon type="FontAwesome" name="envelope" />
<Text>Mon adresse email</Text>
</Button>
<Button
full
rounded
style={{ padding: 10, marginTop: 20 }}
onPress={() =>
facebookLogin().then(() => {
this.setState({ authentificated: true });
})
}
>
<Icon type="FontAwesome" name="facebook" />
<Text style={{ color: "#fff" }}>Mon compte Facebook</Text>
</Button>
</Container>
</LinearGradient>
);
}
}
const styles = StyleSheet.create({
backgroundImage: {
flex: 1,
width: "100%",
height: "100%",
justifyContent: "center",
alignItems: "center",
backgroundColor: "transparent",
padding: 25
},
logo: {
width: 170,
height: 130
},
loginText: {
paddingTop: 50,
paddingBottom: 50,
color: "#fff"
}
});

this.setState() should be called from inside the React component. You are wrongly calling it inside facebookLogin() and loginUser() functions.
You can fix it like this:
export async function loginUser(email, password) {
try {
return firebase
.auth()
.signInWithEmailAndPassword(email, password)
} catch (error) {
console.log(error.toString);
}
}
then in your component, you call
loginUser().then(() => {
this.setState({ authentificated: true });
});
But please make sure the method where you call, this is properly bound.
The common practice is to define methods like this:
renderCurrentState = () => {
}
Otherwise you would have to do the binding in component's constructor:
constructor(props) {
super(props);
// ...
this.renderCurrentState = this.renderCurrentState.bind(this);
}
What I have done is change loginUser() to return a promise. Then you use the function inside your component.
EDIT:
You can add a prop, eg. onLogin which you can use in Login component to update the authenticated state.
renderCurrentState() {
if (this.state.authentificated) {
return <Welcome />;
} else {
return <EmailLoging onLogin={this.updateState} />;
}
}
updateState = () => {
this.setState({ authentificated: true });
// possibly other code
}
You should call onLogin on loginUser().then(() => { ... })

Related

RTK Query Error: 'AbortError: Aborted' while running test

I'm trying to run a test on login form submit which goes through a Rest API call to authenticate a user.
I have configured MSW for mocking the rest API. Whenever I am running the npm test command the rest api call isn't going through and returning an error. Seems like the mock API isn't working in this case
I have configured MSW for mocking the rest API. I am attaching the handler file, jest setup file and screen file below for reference.
jest.setup.config
import mockAsyncStorage from '#react-native-async-storage/async-storage/jest/async-storage-mock';
import 'whatwg-fetch';
global.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
jest.mock('#react-native-async-storage/async-storage', () => mockAsyncStorage);
login.screen.tsx
import React from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { Button, Pressable, SafeAreaView, Text, View } from 'react-native';
import styles from './EmailLogin.style';
import Input from '../../components/Input/Input.component';
import { color } from '../../theme';
import LinearGradient from 'react-native-linear-gradient';
import { setUser } from '../../stores/user.reducer';
import { useLoginUserMutation } from '../../services/api/auth';
import { useAppDispatch } from '../../hooks/redux';
const EMAIL_PATTERN = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,}$/i;
interface IEmailFormInputs {
email: string;
password: string;
}
const EmailLogin: React.FC = ({ navigation }: any) => {
const dispatch = useAppDispatch();
const [loginUser, { isLoading, isError, error, isSuccess }] =
useLoginUserMutation();
const onSubmit: SubmitHandler<IEmailFormInputs> = async requestData => {
try {
const { result } = await loginUser(requestData).unwrap();
dispatch(setUser(result));
navigation.navigate('Home');
} catch (err) {
console.log(err);
}
};
const {
control,
handleSubmit,
formState: { errors },
} = useForm<IEmailFormInputs>({
mode: 'onChange',
defaultValues: {
email: '',
password: '',
},
});
return (
<SafeAreaView style={styles.whiteBackground}>
<View style={styles.mainContainer}>
<View style={styles.welcomeTextContainer}>
<Text style={styles.welcomeTextTitle}>HELLO,</Text>
<Text style={styles.welcomeTextSubTitle}>Welcome back</Text>
</View>
<View style={styles.inputContainer}>
<Input
name="email"
control={control}
rules={{
pattern: {
value: EMAIL_PATTERN,
message: 'Invalid email address',
},
}}
error={errors.email}
placeholder={'Email'}
autoCapitalize={'none'}
autoCorrect={false}
/>
</View>
<View style={styles.inputContainer}>
<Input
name="password"
control={control}
rules={{
minLength: {
value: 3,
message: 'Password should be minimum 3 characters long',
},
}}
secureTextEntry={true}
error={errors.password}
placeholder={'Password'}
autoCapitalize={'none'}
autoCorrect={false}
/>
</View>
<Pressable onPress={handleSubmit(onSubmit)}>
<LinearGradient
start={{ x: 0, y: 0 }}
end={{ x: 1, y: 0 }}
colors={color.gradient.primary}
style={styles.buttonContainer}>
<Text style={styles.buttonText}>Login</Text>
</LinearGradient>
</Pressable>
</View>
</SafeAreaView>
);
};
export default EmailLogin;
login.spec.js
import React from 'react';
import { render, screen, fireEvent, waitFor, act } from '../../test-utils';
import { server } from '../../mocks/server';
import EmailLogin from './EmailLogin.screen';
describe('Home', () => {
//handles valid input submission
it('handle valid form submission', async () => {
await render(<EmailLogin />);
await act(async () => {
fireEvent(
screen.getByPlaceholderText('Email'),
'onChangeText',
'sample#email.com',
);
fireEvent(
screen.getByPlaceholderText('Password'),
'onChangeText',
'password',
);
fireEvent.press(screen.getByText('Login'));
//expected result on success login to be mentioned here
});
});
});
mocks/handler.js
import { rest } from 'msw';
import config from '../config';
export const handlers = [
rest.post(`*url*/user/auth`, (req, res, ctx) => {
console.log(req);
// successful response
return res(
ctx.status(200),
ctx.json({
success: true,
result: {
auth_token: ['authtoken'],
email: req.bodyUsed.email,
id: 1,
first_name: 'xxx',
last_name: 'xxx',
number: 'xxxxxxx',
user_state: 1,
phone_verified: true,
},
}),
);
}),
];
I get the following error when
console.log
{ status: 'FETCH_ERROR', error: 'AbortError: Aborted' }
at src/screens/EmailLogin/EmailLogin.screen.tsx:32:15
at Generator.throw (<anonymous>)

losing my mind - why doesn't my fetch re render (redux)

In my project I have many users and many resources (and many user_resources/the join between users and resources).When I POST to user_resources I see it work on my rails backend (as in I see that instance posted) but in my react native front end I don't see it listed upon update. However, once the app is completely refresh (when I stop and restart the expo server), I finally see those items rendered. ANY IDEAS? I've been working on this forever now to no avail and my project is due tmrw, so any help is appreciated.
screen where I post to user_resources:
import React from 'react';
import { ScrollView,SafeAreaView,StyleSheet, Text, View, FlatList, TouchableOpacity,Button, NativeEventEmitter} from 'react-native';
import {connect} from 'react-redux';
import {fetchResources,searchChanged} from '../actions';
import { addUserResource } from '../actions'
import {SearchBar} from 'react-native-elements';
import { MaterialIcons } from '#expo/vector-icons';
import { MaterialCommunityIcons } from '#expo/vector-icons';
class ResourcesScreen extends React.Component {
state = {
search: ''
}
componentDidMount = () =>{
this.props.fetchResources();
}
FlatListItemSeparator = () => {
return (
<View
style={{
height: 0.5,
width: "100%",
backgroundColor: "lightblue",
}}
/>
);
}
handlePress(item) {
debugger
fetch('http://localhost:3000/user_resources', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json'
},
body: JSON.stringify({
resource_id: item.id,
user_id: this.props.users.id,
name: item.name,
description:item.description,
link:item.link,
})
})
.then(res => res.json())
.then(data2 => {
console.log(data2)
this.props.addUserResource(data2)
console.log(this.props)
})
}
header = () => {
return <View>
<Text style={styles.header}>Resources</Text>
</View>
}
onSearchChange = text => {
this.setState({search:text})
}
render(){
return(
<SafeAreaView>
<SearchBar placeholderTextColor="white" placeholder="Enter resource name here" onChangeText={this.onSearchChange} value={this.state.search}/>
<TouchableOpacity onPress={() => this.props.navigation.navigate('Add A New Resource',{topicId:this.props.route.params.topicId})} style={styles.buttonitem}>
<Text style={styles.text}>
<MaterialIcons name="add-circle-outline" size={24} color="white"/>Add A New Resource
</Text>
</TouchableOpacity>
<FlatList keyExtractor={(item)=> item.id.toString()} data={this.props.resourceName} ItemSeparatorComponent = { this.FlatListItemSeparator } renderItem={({item}) => {
return <TouchableOpacity style={styles.material2}>
<Text onPress={() => this.props.navigation.navigate('Add A New Resource',{topicId:item.id})} style={styles.listitem}>{item.name}</Text>
<MaterialCommunityIcons name="bookmark-plus" size={50} color="#16a085" backgroundColor='black' onPress={()=>this.handlePress(item)}/>
</TouchableOpacity>
}}
ListHeaderComponent = {this.header}/>
</SafeAreaView>
)
}
}
const mapStateToProps = (state) => {
return {
resourceName: state.resourceReducer.resources,
users: state.userReducer,
search:state.resourceReducer.searchTerm
}
}
const mapDispatchToProps = (dispatch) => {
return {
fetchResources: () => dispatch(fetchResources()),
addUserResource,
searchChanged
}
}
export default connect(mapStateToProps,mapDispatchToProps)(ResourcesScreen)
After this I head to the profile page where the user_resources SHOULD be displayed, but aren't
import React from 'react';
import { ScrollView,StyleSheet, Text, View, FlatList, TouchableOpacity} from 'react-native';
import {connect} from 'react-redux';
import {SearchBar} from 'react-native-elements';
import { AntDesign } from '#expo/vector-icons';
class Profile extends React.Component{
handleDelete = (id) => {
debugger
fetch(`http://localhost:3000/user_resources/${id}`, {
method: "DELETE",
headers: {
"Authorization": this.props.users.token
}
})
.then(r => r.json())
.then((delResource) => {
console.log(delResource)
this.props.deleteOneFood(delResource)
console.log('deleted')
this.forceUpdate()
})
}
render(){
return(
<View>
{this.props.users.user_resources.map(singleResource=> {
return <Text key={singleResource.id}>{singleResource.name}</Text>
})}
</View>
)}
}
let deleteOneResource = (id) => {
return {
type: "DELETE_ONE_USER_RESOURCE",
payload: id
}
}
const mapDispatchToProps = {
deleteOneResource
}
const mapStateToProps = (state) => {
return {
users: state.userReducer,
}
}
export default connect(mapStateToProps,mapDispatchToProps)(Profile)
I had a flatlist before but thought that may be causing the issues so rendered it another way, still no luck. I tried forceUpdates as well, still no luck. I'm not sure if the issue is coming from my reducer:
let userInitialState = {
id: 0,
username: "",
name: '',
category: '',
token: "",
user_resources:[],
}
let userReducer = (state = userInitialState, action) => {
switch(action.type){
case "ADD_USERS":
let singleNestedObject = {
...action.users.user,
token: action.users.token
}
return {
...state,
username: action.users.user.username,
token: action.users.token,
id: action.users.user.id,
name: action.users.user.name,
category: action.users.user.category,
user_resources: action.users.user.user_resources
}
case "ADD_ONE_USER_RESOURCE":
let copyOfResources = [...state.user_resources, action.userResources]
return {
...state,
user_resources: copyOfResources
}
default:
return state
}
}
and it's action
export const addUserResource = (resourceInfo) => {
return {
type: "ADD_ONE_USER_RESOURCE",
userResources: resourceInfo
}
}
Please help me find the issue here, I'm losing it.

Uhandled atob variable on screen rendering

The error I get is [Unhandled promise rejection: ReferenceError: Can't find variable: atob].
And my screen code:
import React, { Component } from "react";
import { View, StatusBar, Text } from "react-native";
import firebase from "firebase";
import "firebase/firestore";
import { RowItem } from "../components/RowItem";
import { Header, Left, Right, Icon } from "native-base";
const styles = {
container: {
flexDirection: "row",
flexWrap: "wrap",
padding: 20
}
};
class QuizIndex extends Component {
constructor(props) {
super(props);
this.state = {
docs: []
};
}
async componentDidMount() {
await this.quizes();
}
quizes = async () => {
let result = await firebase
.firestore()
.collection("quiz")
.where("parentId", "==", "")
.get()
.then(r => {
console.log("fine");
})
.catch(e => {
console.log("Not fine");
});
const docs = result.docs.map(doc => {
return { uid: doc.id, ...doc.data() };
});
return this.setState({ docs });
};
render() {
return (
<View style={styles.container}>
<StatusBar barStyle="dark-content" />
{this.state.docs.map(doc => (
<RowItem
key={doc.uid}
parentId={doc.parentId}
name={doc.title}
color={doc.color}
icon={doc.icon}
onPress={() =>
this.props.navigation.navigate("QuizSub", {
title: doc.title,
color: doc.color,
parentId: doc.uid
})
}
/>
))}
</View>
);
}
}
export default QuizIndex;
I don't get it where this problem occur because the things were working fine. Do you have any suggestion about this ? I googled it but none of the solutions helped me.
It's an issue in firebase dependency
Try to use version 7.9.0, this version will work fine.
yarn add firebase#7.9.0
I think if you install the base-64 npm package it will solve, but don't quite know why this is happening.
yarn add base-64
#or
npm install base-64
At App.js add:
import {decode, encode} from 'base-64'
if (!global.btoa) { global.btoa = encode }
if (!global.atob) { global.atob = decode }

Lodash debounce not working all of a sudden?

I'm using a component I wrote for one app, in a newer app. The code is like 99% identical between the first app, which is working, and the second app. Everything is fine except that debounce is not activating in the new app. What am I doing wrong?
// #flow
import type { Location } from "../redux/reducers/locationReducer";
import * as React from "react";
import { Text, TextInput, View, TouchableOpacity } from "react-native";
import { Input } from "react-native-elements";
import { GoogleMapsApiKey } from "../../.secrets";
import _, { debounce } from "lodash";
import { connect } from "react-redux";
import { setCurrentRegion } from "../redux/actions/locationActions";
export class AutoFillMapSearch extends React.Component<Props, State> {
textInput: ?TextInput;
state: State = {
address: "",
addressPredictions: [],
showPredictions: false
};
async handleAddressChange() {
console.log("handleAddressChange");
const url = `https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${GoogleMapsApiKey}&input=${this.state.address}`;
try {
const result = await fetch(url);
const json = await result.json();
if (json.error_message) throw Error(json.error_message);
this.setState({
addressPredictions: json.predictions,
showPredictions: true
});
// debugger;
} catch (err) {
console.warn(err);
}
}
onChangeText = async (address: string) => {
await this.setState({ address });
console.log("onChangeText");
debounce(this.handleAddressChange.bind(this), 800); // console.log(debounce) confirms that the function is importing correctly.
};
render() {
const predictions = this.state.addressPredictions.map(prediction => (
<TouchableOpacity
style={styles.prediction}
key={prediction.id}
onPress={() => {
this.props.beforeOnPress();
this.onPredictionSelect(prediction);
}}
>
<Text style={text.prediction}>{prediction.description}</Text>
</TouchableOpacity>
));
return (
<View>
<TextInput
ref={ref => (this.textInput = ref)}
onChangeText={this.onChangeText}
value={this.state.address}
style={[styles.input, this.props.style]}
placeholder={"Search"}
autoCorrect={false}
clearButtonMode={"while-editing"}
onBlur={() => {
this.setState({ showPredictions: false });
}}
/>
{this.state.showPredictions && (
<View style={styles.predictionsContainer}>{predictions}</View>
)}
</View>
);
}
}
export default connect(
null,
{ setCurrentRegion }
)(AutoFillMapSearch);
I noticed that the difference in the code was that the older app called handleAddressChange as a second argument to setState. Flow was complaining about this in the new app so I thought async/awaiting setState would work the same way.
So changing it to this works fine (with no flow complaints for some reason. maybe because I've since installed flow-typed lodash. God I love flow-typed!):
onChangeText = async (address: string) => {
this.setState(
{ address },
_.debounce(this.handleAddressChange.bind(this), 800)
);
};

React native signed APK crash

Signed APK crash after launch, in logCat i got requiring unknown module 'React'
Debug application works fine, but in logCat i got >> Requiring module 'React' by name is only supported for debugging purposes and will BREAK IN PRODUCTION!
React v15.4.1, React native v0.39.2 ?
Sorry for my english
this is my index.android.js
import React from 'react';
import {AppRegistry} from 'react-native';
import myapp from './index_start.js';
AppRegistry.registerComponent('myapp', () => myapp);
and index_start.js
import React, { Component } from "react";
import {
StyleSheet,
AppRegistry,
Text,
Image,
View,
AsyncStorage,
NetInfo,
StatusBar,
Navigator,
Dimensions
} from 'react-native';
// Window dismensions
const { width, height } = Dimensions.get('window');
// Device infos
import DeviceInfo from 'react-native-device-info';
// Native SplashScreen
import SplashScreen from 'react-native-splash-screen';
// Spinner
import Spinner from 'react-native-spinkit';
// Models
import User from './model/UserModel';
// Json data for initial launch
var DB = require('./DB.json');
// Components
import Stage from './components/stage/stage.js'
import Player from './components/player/player.js'
import Settings from './components/settings/settings.js'
import House from './stages/house/house.js'
// LocalStorage key
var USER_KEY = 'user_key';
const routes = [
{name: 'loading'},
{name: 'stage', component: Stage},
{name: 'house', component: House},
{name: 'settings', component: Settings}
];
const _navigator = null;
export default class myapp extends Component {
constructor(props) {
super(props);
this.state = {
isConnected: false,
isLoading: true,
_navigator: null,
stages: null
}
}
componentWillMount() {
// check if connected
this._checkConnexionType();
}
componentDidMount() {
SplashScreen.hide();
this._loadInitialData();
}
componentDidUpdate() {
// console.log(this.state.stages)
if (!this.state.isLoading && this.state.stages !== null) {
_navigator.push({
name: 'stage',
passProps: {
data: this.state.stages
}
})
}
}
/**
* Load localStorage Data
*/
async _loadInitialData() {
// GET User LocalStorage
if (this.state.stages == null) {
var localData;
//AsyncStorage.removeItem(USER_KEY)
AsyncStorage.getItem(USER_KEY).then((data) => {
if (data !== null) {
var localData = JSON.parse(data);
// User.uuid = localData.uuid;
User.setStages(localData.stages)
this.setState({
'stages' : localData.stages
})
} else {
var storage = {};
storage.setUiid = DeviceInfo.getUniqueID();
storage.stages = DB.stages;
AsyncStorage.setItem(USER_KEY, JSON.stringify(storage));
this.setState({
'stages' : DB.stages
})
}
})
}
if (this.state.isConnected) {
// var rStages = this._loadRemoteStages();
// console.log(rStages);
}
// Change state
setTimeout((function() {
this.setState({
'isLoading': false
})
}).bind(this), 1500);
}
/**
* GET stages from remote DB
*/
async _loadRemoteStages() {
await fetch(API_URL)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson)
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
/**
* CHECK IF user is connected to Network
* SET bool to state isLoading
*/
_checkConnexionType() {
NetInfo.isConnected.fetch().then(response => {
this.setState({ isConnected: response})
})
}
_renderScene(route, navigator) {
_navigator = navigator;
if (route.name == 'loading') {
return (
<View style={styles.container}>
<StatusBar hidden={true} />
<Image
style={{width: width, height: height}}
source={require('./img/screen.jpg')}
/>
<View style={styles.loading}>
<Text style={styles.loadingText}>CHARGEMENT</Text>
<Spinner type="ThreeBounce" color={'#fff'}/>
</View>
</View>
)
} else if (route.name == 'stage') {
return (
<Stage navigator={_navigator} {...route.passProps}/>
)
} else if (route.name == 'player') {
return (
<House navigator={_navigator} {...route.passProps}}/>
)
} else if (route.name == 'settings') {
return (
<Settings navigator={_navigator} {...route.passProps}/>
)
}
}
render() {
return (
<Navigator
initialRoute={{name: 'loading'}}
configureScene={() => Navigator.SceneConfigs.FloatFromBottomAndroid}
renderScene={this._renderScene.bind(this)}
/>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
loading: {
flex: 1,
position: 'absolute',
bottom: 50,
left: 0,
right: 0,
alignItems: 'center',
},
loadingText:{
flex: 1,
fontFamily: 'CarterOne',
fontSize: 20,
color: '#fff'
}
});