React Native Failed to ImportScripts Error - reactjs

I'm getting an ImportScripts error which means I'm not importing or exporting something correctly I'm guessing. I've narrowed it down to the import { getPath } from '~/redux/modules/camera' line. But I'm not sure why I get an error. I import connect so I have access to dispatch and then I import the getPath function. What else should I be doing? Thanks!
import React, { PropTypes, Component } from 'react';
import {
Dimensions,
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
import Camera from 'react-native-camera'
import { connect } from 'react-redux'
import { getPath } from '~/redux/modules/camera'
class NimbusCamera extends Component {
static propTypes = {
navigator: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
}
state = {
camera: {
aspect: Camera.constants.Aspect.fill,
captureTarget: Camera.constants.CaptureTarget.disk,
type: Camera.constants.Type.front,
orientation: Camera.constants.Orientation.auto,
flashMode: Camera.constants.FlashMode.auto,
}
isRecording: false,
timeLeft: 30,
limitReached: false
}
render() {
console.log(this.props)
return (
<View style={styles.container}>
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={this.state.camera.aspect}
type={this.state.camera.type}
captureTarget={this.state.camera.captureTarget}
captureAudio={true}
flashMode={this.state.camera.flashMode}
>
<Text style={styles.capture} onPress={this.startRecording.bind(this)}>[CAPTURE]</Text>
<Text style={styles.capture} onPress={this.stopRecording.bind(this)}>[STOP_RECORDING]</Text>
</Camera>
</View>
);
}
startRecording = () => {
if (this.camera) {
this.camera.capture({mode: Camera.constants.CaptureMode.video})
.then((data) => console.log(data))
.catch(err => console.error(err));
this.setState({
isRecording: true
});
let timerId = setInterval(countdown, 1000);
function countdown() {
if (this.state.timeLeft === 0) {
clearTimeout(timerId);
this.setState({isRecording: false})
} else {
this.setState({timeLeft: this.state.timeLeft--})
}
}
}
}
stopRecording = () => {
if (this.camera) {
this.camera.stopCapture();
this.setState({
isRecording: false
});
}
}
}
export default connect()(NimbusCamera)
const styles = StyleSheet.create({
container: {
flex: 1
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
height: Dimensions.get('window').height,
width: Dimensions.get('window').width
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});
Here is my redux camera module.
const GET_PATH = 'GET_PATH'
const CLEAR_PATH = 'CLEAR_PATH'
initialState = {
videoPath: ''
}
export function getPath (path) {
return {
type: GET_PATH,
path
}
}
export function clearPath () {
return {
type: CLEAR_PATH
}
}
export default function camera (state = initialState, action) {
switch (action.type) {
case GET_PATH :
return {
...state,
videoPath: action.path
}
case CLEAR_PATH :
return {
...state,
videoPath: ''
}
default :
return state
}
}

Any log in your packager console? usually it print much more detail error info.

errors like these pops-up also when you make a typo in your code. Then module cannot be properly imported. Check your code for typos first :)

Related

In react-native scrollToOffset in flat list is not working properly?

In flatlist scroll to offset is not working properly when the no of items are less than 3. If the no of items are greater or equal to 3 than it is working exactly fine.
import React, { Component } from 'react'
import { Animated, Dimensions, RefreshControl, StyleSheet, View, TouchableOpacity } from 'react-native'
import { HEADER_HEIGHT } from '.'
import { CustomText, FlatListWrapper, FlatListWrapperProps } from '../../../common-library/components'
import { ScrollValueContext } from './Context'
import { get } from 'lodash'
import { CENTER, colors, dimens, ROW, SPACE_BETWEEN } from '../../../common-library/config'
import { TAB_BAR_HEIGHT } from './CommunityHeaderComponent'
import { IconButtonWrapper } from '../generic'
import { icons } from '../../common'
import { log } from '../../config'
const labels = {
GO_TO_TOP: 'Go to Top'
}
const styles = StyleSheet.create({
contentStyle: {
paddingTop: HEADER_HEIGHT
},
scrollToTopContainer: {
position: 'absolute',
top: TAB_BAR_HEIGHT,
alignItems: 'center',
left: 0,
right: 0,
zIndex: 999
},
buttonsContainer: {
borderColor: colors.DuckBlue,
backgroundColor: colors.DuckBlue,
borderRadius: dimens.size25,
width: 110,
flexDirection: ROW,
justifyContent: SPACE_BETWEEN,
paddingVertical: dimens.size10,
alignItems: CENTER
},
buttonCta: {
paddingLeft: dimens.size15
},
goToTopLabel: {
color: colors.White,
textAlign: CENTER
},
crossIconCta: {
justifyContent: CENTER,
alignItems: CENTER,
paddingRight: dimens.size15
// paddingTop: dimens.size2
}
})
interface State {
shouldRefresh?: boolean
showScrollToTopView?: boolean
dontShowGoToTop?: boolean
}
interface Props extends FlatListWrapperProps {
uniqueKey?: string
getFlatListRef?: (ref) => any
getScrolledPosition?: (contentOffset) => any
onPullToRefresh?: () => any
renderScrollToTopView?: boolean
}
export class StickyScrollableFlatlistComponent extends Component<Props, State> {
flatListRef
scrolledValue
timerRef
state = {
shouldRefresh: false,
showScrollToTopView: false,
dontShowGoToTop: false
}
componentDidUpdate(prevProps) {
const { showScrollToTopView, dontShowGoToTop } = this.state
if ((!prevProps.isFetching && this.props.isFetching) || (prevProps.isFetching && !this.props.isFetching)) {
if ((showScrollToTopView || dontShowGoToTop) && this.props.renderScrollToTopView) {
this.setState({
showScrollToTopView: false,
dontShowGoToTop: false
})
}
setTimeout(() => {
log('setTileout is called', this.scrolledValue > HEADER_HEIGHT, this.scrolledValue)
this.flatListRef.scrollToOffset({
offset: this.scrolledValue > HEADER_HEIGHT ? HEADER_HEIGHT : HEADER_HEIGHT,
animated: false
})
}, 2000)
}
}
onRefresh = () => {
const { onPullToRefresh } = this.props
if (onPullToRefresh) {
this.setState({
shouldRefresh: true
})
onPullToRefresh().then(() => {
this.setState({
shouldRefresh: false
})
})
}
}
showScrollToTopView = () => {
const { showScrollToTopView } = this.state
const DEVICE_HEIGHT = Dimensions.get('window').height
if (this.scrolledValue >= 2 * DEVICE_HEIGHT - HEADER_HEIGHT && !showScrollToTopView) {
this.setState({
showScrollToTopView: true
})
} else if (this.scrolledValue <= DEVICE_HEIGHT - HEADER_HEIGHT && showScrollToTopView) {
this.setState({
showScrollToTopView: false
})
}
}
onClikCrossIcon = () => {
this.setState({
dontShowGoToTop: true,
showScrollToTopView: false
})
}
moveToTop = () => {
this.flatListRef.scrollToOffset({
offset: HEADER_HEIGHT,
animated: true
})
}
renderScrollToTopView = () => {
return (
<View style={styles.scrollToTopContainer}>
<View style={styles.buttonsContainer}>
<TouchableOpacity onPress={this.moveToTop} style={styles.buttonCta} activeOpacity={1}>
<CustomText textStyle={styles.goToTopLabel}>{labels.GO_TO_TOP}</CustomText>
</TouchableOpacity>
<TouchableOpacity onPress={this.onClikCrossIcon} style={styles.crossIconCta} activeOpacity={1}>
<IconButtonWrapper iconImage={icons.CROSSWHITE_ICON} iconHeight={dimens.size10} iconWidth={dimens.size10} />
</TouchableOpacity>
</View>
</View>
)
}
render() {
const { shouldRefresh, showScrollToTopView, dontShowGoToTop } = this.state
const { getFlatListRef, uniqueKey, getScrolledPosition, renderScrollToTopView = false } = this.props
return (
<ScrollValueContext.Consumer>
{(context) => (
<>
{showScrollToTopView && !dontShowGoToTop && renderScrollToTopView && this.renderScrollToTopView()}
<FlatListWrapper
{...this.props}
onScroll={Animated.event([{ nativeEvent: { contentOffset: { y: context.scrollYValue } } }], {
useNativeDriver: true,
listener: ({ nativeEvent }) => {
const yOffsetValue = get(nativeEvent, 'contentOffset.y', 0)
log('Flatlist wrapper on event is called', yOffsetValue)
this.scrolledValue = yOffsetValue
// context.scrollYValue.setValue(this.scrolledValue)
{
renderScrollToTopView && this.showScrollToTopView()
}
if (getScrolledPosition) {
getScrolledPosition(yOffsetValue)
}
}
})}
refreshControl={
<RefreshControl
refreshing={shouldRefresh}
progressViewOffset={HEADER_HEIGHT}
onRefresh={() => {
this.onRefresh()
}}
/>
}
showCustomizedAnimatedFlatList={true}
contentContainerStyle={[styles.contentStyle, this.props.contentContainerStyle]}
scrollEventThrottle={16}
inputRef={(ref) => {
log('inputRefinputRefis called')
if (ref) {
this.flatListRef = ref
if (getFlatListRef) {
getFlatListRef(ref)
}
context.addFlatListRef(this.flatListRef, uniqueKey)
}
}}
onMomentumScrollEnd={({ nativeEvent }) => {
const { contentOffset } = nativeEvent
if (contentOffset.y === 0) {
log('inside onMomentumScrollEnd')
context.flatListRef.forEach((item) => {
if (item.key !== uniqueKey) {
item.value.scrollToOffset({
offset: 0,
animated: false
})
}
})
}
}}
/>
</>
)}
</ScrollValueContext.Consumer>
)
}
}
So my code is like this. where flatlist wrapper is just the wrapper of flatlist.
In flatlist scroll to offset is not working properly when the no of items are less than 3. If the no of items are greater or equal to 3 than it is working exactly fine.

Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method React Native

I'm trying to test a useState value of and object in react native with redux.
I got this error when i have to store a value in state using react-Redux..
I want to store notes and numbers in two arrasy with react native redux and perform both action with single store.Any help is greatly appreciated
Component:
import React, { useState } from 'react'
import { View, StyleSheet } from 'react-native'
import { IconButton, TextInput, FAB } from 'react-native-paper'
import Header from '../components/Header'
function AddNote({ navigation }) {
const [noteTitle, setNoteTitle] = useState('')
const [noteValue, setNoteValue] = useState('')
function onSaveNote() {
navigation.state.params.addNote({ noteTitle, noteValue })
navigation.goBack();
}
return (
<>
<Header titleText='Add a new note' />
<IconButton
icon='close'
size={25}
color='white'
onPress={() => navigation.goBack()}
style={styles.iconButton}
/>
<View style={styles.container}>
<TextInput
label='Add Title Here'
value={noteTitle}
mode='outlined'
onChangeText={setNoteTitle}
style={styles.title}
/>
<TextInput
label='Add Note Here'
value={noteValue}
onChangeText={setNoteValue}
mode='flat'
multiline={true}
style={styles.text}
scrollEnabled={true}
returnKeyType='done'
blurOnSubmit={true}
/>
<FAB
style={styles.fab}
small
icon='check'
disabled={noteTitle == '' ? true : false}
onPress={() => onSaveNote()}
/>
</View>
</>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
paddingHorizontal: 20,
paddingVertical: 20
},
iconButton: {
backgroundColor: 'rgba(46, 113, 102, 0.8)',
position: 'absolute',
right: 0,
top: 40,
margin: 10
},
title: {
fontSize: 24,
marginBottom: 20
},
text: {
height: 300,
fontSize: 16
},
fab: {
position: 'absolute',
margin: 20,
right: 0,
bottom: 0
}
})
export default AddNote
Reducers:
import remove from 'lodash.remove'
// Action Types
export const ADD_NOTE = 'ADD_NOTE'
export const DELETE_NOTE = 'DELETE_NOTE'
export const ADD_NUMBER = 'ADD_NUMBER'
export const DELETE_NUMBER = 'DELETE_NUMBER'
// Action Creators
let noteID = 0
let numberID = 0
export function addnote(note) {
return {
type: ADD_NOTE,
id: noteID++,
note
}
}
export function deletenote(id) {
return {
type: DELETE_NOTE,
payload: id
}
}
export function addnumber(number) {
return {
type: ADD_NUMBER,
id: numberID++,
number
}
}
export function deletenumber(id) {
return {
type: DELETE_NUMBER,
payload: id
}
}
// reducer
const INITIAL_STATE = {
note: [], //note array for save notes
number: [] // number array for save numbers
};
function notesReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case ADD_NOTE:
return [
...state,
{
id: action.id,
note: action.note
}
]
case DELETE_NOTE:
const deletedNewArray = remove(state, obj => {
return obj.id != action.payload
})
return deletedNewArray
case ADD_NUMBER:
return [
...state,
{
id: action.id,
number: action.number
}
]
case DELETE_NUMBER:
deletedNewArray = remove(state, obj => {
return obj.id != action.payload
})
return deletedNewArray
default:
return state
}
}
export default notesReducer
So What should i do it..
Please Help Me..
The reducer must return the new state instead of the updated parameter:
// reducer
const INITIAL_STATE = {
note: [], //note array for save notes
number: [] // number array for save numbers
};
function notesReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case ADD_NOTE:
return {
...state,
note: [
...state.note,
{
id: action.id,
note: action.note
}
]
};
case DELETE_NOTE:
const note = remove(state.note, obj => obj.id != action.payload);
return {...state, note};
case ADD_NUMBER:
return {
...state,
number: [
...state.number,
{
id: action.id,
number: action.number
}
]
};
case DELETE_NUMBER:
const number = remove(state.number, obj => obj.id != action.payload);
return {...state, number}
default:
return state
}
}

Why does the header icon load slowly in react-native?

I'm using both Stack Navigations and Draw Navigations at the same time.
"react-navigation": "3.0.4"
My App.js
import React, { Component } from "react";
import HomeScreen from "./screen/HomeScreen";
export default class AwesomeApp extends Component {
constructor() {
super();
this.state = {
isReady: false
};
}
async componentWillMount() {
await Expo.Font.loadAsync({
Roboto: require("native-base/Fonts/Roboto.ttf"),
Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
Ionicons: require("native-base/Fonts/Ionicons.ttf")
});
this.setState({ isReady: true });
}
render() {
if (!this.state.isReady) {
return <Expo.AppLoading />;
}
return <HomeScreen />;
}
}
my HomeScreen:
import React, { Component } from "react";
import TestScreen from "../TestScreen";
...
import {
createDrawerNavigator,
createAppContainer,
createStackNavigator
} from "react-navigation";
import { AsyncStorage } from "react-native";
import Expo, { Constants, LocalAuthentication } from "expo";
import TouchID from "react-native-touch-id";
import crypto from "crypto";
import safeCrypto from "react-native-fast-crypto";
import { asyncRandomBytes } from "react-native-secure-randombytes";
const defaultNavigationOptions = {
headerTintColor: "black",
headerStyle: {
borderBottomColor: "#fff",
borderBottomWidth: 1,
shadowColor: "transparent",
elevation: 0
},
headerTitleStyle: {
fontWeight: "bold",
fontSize: 18
}
};
window.randomBytes = asyncRandomBytes;
window.scryptsy = safeCrypto.scrypt;
let pinnumbercheck = AsyncStorage.getItem("pinnumber");
let powersucesscheck = AsyncStorage.getItem("powersucess");
let nicknamecheck = AsyncStorage.getItem("nickname");
let compatible = Expo.LocalAuthentication.hasHardwareAsync();
let fingerprints = Expo.LocalAuthentication.isEnrolledAsync();
const Drawers = createDrawerNavigator(
{
FirstAgree: {
screen: UserAcceptanceScreen
},
Test: { screen: TestScreen }
},
{
initialRouteName: "FirstAgree",
contentComponent: props => <SideBar {...props} />
}
);
const SettingStack = createStackNavigator(
{
screen: SettingScreen
},
{
defaultNavigationOptions,
headerLayoutPreset: "center"
}
);
const FirstAgreeStack = createStackNavigator(
{
screen: UserAcceptanceScreen
},
{
defaultNavigationOptions,
headerLayoutPreset: "center"
}
);
const FirstAgreeStack2 = createStackNavigator(
{
screen: UserAcceptanceScreen2
},
{
defaultNavigationOptions,
headerLayoutPreset: "center"
}
);
const WalletScreenStack = createStackNavigator(
{
screen: RegisterWalletScreen2
},
{
defaultNavigationOptions,
headerLayoutPreset: "center"
}
);
const WalletScreen2Stack = createStackNavigator(
{
screen: RegisterWalletScreen3
},
{
defaultNavigationOptions,
headerLayoutPreset: "center"
}
);
const TakeWalletStack = createStackNavigator(
{
screen: TakeWalletScreen
},
{
defaultNavigationOptions,
headerLayoutPreset: "center"
}
);
const RegisterSecurityStack = createStackNavigator(
{
screen: RegisterSecurityScreen
},
{
defaultNavigationOptions,
headerLayoutPreset: "center"
}
);
const RegisterSecurityStack2 = createStackNavigator(
{
screen: RegisterSecurityScreen2
},
{
defaultNavigationOptions,
headerLayoutPreset: "center"
}
);
const PinNumberLoginStack = createStackNavigator(
{
screen: PinNumberLogin
},
{
defaultNavigationOptions,
headerLayoutPreset: "center"
}
);
const TestssStack = createStackNavigator(
{
screen: Testss
},
{
defaultNavigationOptions,
headerLayoutPreset: "center"
}
);
const NickRegisterStack = createStackNavigator(
{
screen: NickRegisterScreen
},
{
defaultNavigationOptions,
headerLayoutPreset: "center"
}
);
const stackScreen = createStackNavigator(
{
Drawers: {
screen: Drawers
},
UserRight: {
screen: UserRightScreen
},
...(very more)
},
{
initialRouteName: "RegisterWalletIndex",
headerMode: "none"
}
);
const HomeScreenRouter = createAppContainer(stackScreen);
export default HomeScreenRouter;
There's nothing wrong with moving between screens and how to use them.
However, the header icon is displayed too late on the next screen when you move the screen.
The header icon is displayed later than the full screen. So you can't act on the screen right away.
usepage.js:
import React from "react";
import {
View,
Text,
TouchableOpacity,
Alert,
Image,
Platform,
ActivityIndicator
} from "react-native";
import { ListItem, CheckBox, Body } from "native-base";
import styles from "./styles.js";
import { Ionicons } from "#expo/vector-icons";
import { NavigationActions } from "react-navigation";
class UserAcceptanceScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
allCheckbox: false,
checkbox1: false,
checkbox2: false,
checkbox3: false,
loading: false
};
}
static navigationOptions = ({ navigation }) => {
return {
headerLeft: (
<TouchableOpacity
style={{ paddingLeft: 15 }}
onPress={() => navigation.dispatch(NavigationActions.back())}
>
<Ionicons name={"ios-arrow-back"} size={35} color={"black"} />
</TouchableOpacity>
)
};
};
componentDidMount() {
this.setState({
loading: true
});
}
allToggleSwitch() {
this.setState({
allCheckbox: !this.state.allCheckbox
});
}
toggleSwitch1() {
this.setState({
checkbox1: !this.state.checkbox1
});
}
toggleSwitch2() {
this.setState({
checkbox2: !this.state.checkbox2
});
}
toggleSwitch3() {
this.setState({
checkbox3: !this.state.checkbox3
});
}
render() {
return this.state.loading === false ? (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<ActivityIndicator size="large" />
</View>
) : (
<View style={styles.container}>
...
</View>
);
}
}
export default UserAcceptanceScreen;
I don't know why because I did what I wanted. Is there something I'm missing?
Please give us a lot of feedback and help.
I didn't know why it was loading slowly, but I solved this problem by designing one loading screen.
My use loading Screen Page:
import React, { Component } from "react";
import {
AsyncStorage,
Text,
View,
ActivityIndicator,
TouchableOpacity
} from "react-native";
import { Ionicons } from "#expo/vector-icons";
class StartScreen extends Component {
constructor(props) {
super(props);
this.state = {
isReady: false
};
}
static navigationOptions = ({ navigation }) => {
return {
headerLeft: (
<TouchableOpacity
style={{ paddingLeft: 15 }}
onPress={() => navigation.navigate("FirstAgreeStack")}
>
<Ionicons name={"ios-arrow-back"} size={35} color={"#ffffff"} />
</TouchableOpacity>
),
headerRight: null
};
};
async componentWillMount() {
let powersucess = await AsyncStorage.getItem("powersucess");
let keystoredata = await AsyncStorage.getItem("keystoredata");
let nickname = await AsyncStorage.getItem("nickname");
let pinnumber = await AsyncStorage.getItem("pinnumber");
let useTouchId = await AsyncStorage.getItem("useTouchId");
powersucess === null
? this.props.navigation.navigate("CusterMizingAlert")
: keystoredata === null
? this.props.navigation.navigate("RegisterWalletIndex")
: nickname === null
? this.props.navigation.navigate("RegisterWalletIndex")
: pinnumber === null
? this.props.navigation.navigate("RegisterSecurity")
: pinnumber === null
? this.props.navigation.navigate("RealPinNumberLogin")
: useTouchId === "useTouchId"
? this.props.navigation.navigate("TouchIdLogin")
: this.props.navigation.navigate("FaceIdLogin"),
this.setState({ isReady: true });
}
render() {
return this.state.isReady === false ? (
<View style={{ flex: 1, alignItems: "center", justifyContent: "center" }}>
<ActivityIndicator size="large" />
</View>
) : (
<View>
<Text>dfdff</Text>
</View>
);
}
}
export default StartScreen;

Loading Component in React native with Firebase and redux

Click here to View Page
I need your help here. I want to add Activity indicator with timeout after Login button is pressed but login button is already configured to loginUser() function! I just need to show activity indicator for some secs and login the user when button is pressed! Thankyou I been trying for week. I'm helpless. So please help me!
import React, { Component } from 'react';
import { StyleSheet, View, Text, Alert, TouchableOpacity, ActivityIndicator } from 'react-native';
import { Form, Input, Item, Button, Label, Body, } from 'native-base';
import { login } from "../actions";
import { Actions } from "react-native-router-flux";
import { connect } from "react-redux";
import { colors } from "../../../colors";
class UserLoginForm extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
};
this.loginUser = this.loginUser.bind(this);
this.loginSuccessCallback = this.loginSuccessCallback.bind(this);
this.loginErrorCallback = this.loginErrorCallback.bind(this);
}
forgotPassword() {
Actions.ForgotPassword();
};
loginSuccessCallback(user) {
};
loginErrorCallback(error) {
switch (error.code) {
case 'auth/user-not-found':
Alert.alert('Error', 'User not found. New user? SignUp');
break;
case 'auth/wrong-password':
Alert.alert('Error', 'Wrong Password');
break;
}
};
loginUser() {
const { email, password } = this.state;
const data = { email, password };
this.props.dispatch(login(data, this.loginSuccessCallback, this.loginErrorCallback));
};
render() {
return (
<View style={styles.container}>
<Form>
<Item floatingLabel>
<Label>Email</Label>
<Input
autoCorrect={false}
autoCapitalize="none"
returnKeyType="done"
onChangeText={(email) => this.setState({ email })} />
</Item>
<Item floatingLabel>
<Label>Password</Label>
<Input
secureTextEntry={true}
autoCorrect={false}
autoCapitalize="none"
returnKeyType="go"
onSubmitEditing={this.loginUser}
onChangeText={(password) => this.setState({ password })} />
</Item>
<Button style={styles.loginButton}
full
rounded
onPress={this.loginUser}>
<Text style={{ fontWeight: 'bold', color: 'white', fontSize: 20 }}>Login</Text>
</Button>
<TouchableOpacity onPress={this.forgotPassword}>
<Text style={styles.forgotButton}>Forgot Password?</Text>
</TouchableOpacity>
<--------------Loading Component ------------------>
<View style={styles.loading}>
<ActivityIndicator
animating={this.state.animating}
style={[{ height: 80 }]}
color="#C00"
size="large"
hidesWhenStopped={true} />
<Text style={{ color: 'red' }}>loading..</Text>
</View>
<------------------------------------------------------------------->
</Form>
</View>
);
}
}
function mapStateToProps(state, props) {
return {
user: state.authReducer.user,
};
}
export default connect(
mapStateToProps,
null
)(UserLoginForm);
const styles = StyleSheet.create({
container: {
marginTop: 10
},
loginButton: {
alignSelf: 'center',
marginTop: 10,
width: 250
},
forgotButton: {
alignSelf: 'center',
marginTop: 15,
color: colors.white
},
loading: {
position: 'absolute',
opacity: 0.5,
height: '50%',
width: '35%',
backgroundColor: 'black',
alignSelf: 'center',
alignItems: 'center',
borderBottomLeftRadius: 20,
borderBottomRightRadius: 20,
borderTopRightRadius: 20,
borderTopLeftRadius: 20,
}
})
Login function goes here..
<--------------------------------------------------------------------------------------------------->
import * as t from "./actionTypes";
import {auth} from "../../config/firebase";
import * as api from "./api";
export function register(data, successCB, errorCB) {
return dispatch => {
api.register(data, function (success, data, error) {
if (success) {
successCB(data);
} else if (error) errorCB(error);
});
};
}
export function checkLoginStatus(callback) {
return dispatch => {
auth.onAuthStateChanged(authUser => {
let isLoggedIn = authUser !== null;
if (isLoggedIn) {
api.getUser(authUser, function (success, {exists, user}, error) {
if (success) {
if (exists) {
dispatch({type: t.USER_LOGGED_IN, data: user});
callback(true, 'user');
}
else {
api.getEmployee(authUser, function (success, {exists, user}, error) {
if (success && exists) {
dispatch({type: t.EMPLOYEE_LOGGED_IN, data: user});
callback(true, 'employee');
} else {
dispatch({type: t.LOGGED_OUT});
callback(false);
}
})
}
} else if (error) {
//unable to get user
dispatch({type: t.LOGGED_OUT});
callback(false);
}
});
} else {
dispatch({type: t.LOGGED_OUT});
callback(false);
}
});
};
}
export function login(data, successCB, errorCB) {
return dispatch => {
api.login(data, function (success, data, error) {
if (success) {
if (data.exists) dispatch({type: t.USER_LOGGED_IN, data: data.user});
successCB(data);
} else if (error) errorCB(error);
});
};
}
export function logout(errorCB) {
return dispatch => {
api.logout(function (success, data, error) {
if (success) {
dispatch({type: t.LOGGED_OUT});
} else if (error) errorCB(error);
});
};
}
export function loginEmployee(data, successCB, errorCB) {
return dispatch => {
api.loginEmployee(data, function (success, data, error) {
if (success) {
if (data.exists) dispatch({type: t.EMPLOYEE_LOGGED_IN, data: data.user});
successCB(data);
} else if (error) errorCB(error);
});
};
}

Unable to resolve module. File doesn't exist. The point is that yesterday it worked while today it shows this error

Image of the error
We use react-native gifted-chat. Interesting fact is that yesterday it worked perfectly while when today we run a simulator it is showing this strange error. We tried the solution recommended in the simulator and did those 3 steps while it still shows the same error. How can it be solved? Here is the code:
import React, {Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
} from 'react-native';
import {GiftedChat, Actions, Bubble, SystemMessage} from 'react-native-gifted-chat';
import CustomActions from '../components/CustomActions';
import CustomView from '../components/CustomView';
export default class MessagesScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
messages: [],
loadEarlier: true,
typingText: null,
isLoadingEarlier: false,
};
this._isMounted = false;
this.onSend = this.onSend.bind(this);
this.onReceive = this.onReceive.bind(this);
this.renderCustomActions = this.renderCustomActions.bind(this);
this.renderBubble = this.renderBubble.bind(this);
this.renderSystemMessage = this.renderSystemMessage.bind(this);
this.renderFooter = this.renderFooter.bind(this);
this.onLoadEarlier = this.onLoadEarlier.bind(this);
this._isAlright = null;
}
componentWillMount() {
this._isMounted = true;
this.setState(() => {
return {
messages: require('./data/messages.js'),
};
});
}
componentWillUnmount() {
this._isMounted = false;
}
onLoadEarlier() {
this.setState((previousState) => {
return {
isLoadingEarlier: true,
};
});
setTimeout(() => {
if (this._isMounted === true) {
this.setState((previousState) => {
return {
messages: GiftedChat.prepend(previousState.messages, require('./data/old_messages.js')),
loadEarlier: false,
isLoadingEarlier: false,
};
});
}
}, 1000); // simulating network
}
onSend(messages = []) {
this.setState((previousState) => {
return {
messages: GiftedChat.append(previousState.messages, messages),
};
});
// for demo purpose
this.answerDemo(messages);
}
answerDemo(messages) {
if (messages.length > 0) {
if ((messages[0].image || messages[0].location) || !this._isAlright) {
this.setState((previousState) => {
return {
typingText: 'React Native is typing'
};
});
}
}
setTimeout(() => {
if (this._isMounted === true) {
if (messages.length > 0) {
if (messages[0].image) {
this.onReceive('Nice picture!');
} else if (messages[0].location) {
this.onReceive('My favorite place');
} else {
if (!this._isAlright) {
this._isAlright = true;
this.onReceive('Alright');
}
}
}
}
this.setState((previousState) => {
return {
typingText: null,
};
});
}, 1000);
}
onReceive(text) {
this.setState((previousState) => {
return {
messages: GiftedChat.append(previousState.messages, {
_id: Math.round(Math.random() * 1000000),
text: text,
createdAt: new Date(),
user: {
_id: 2,
name: 'React Native',
// avatar: 'https://facebook.github.io/react/img/logo_og.png',
},
}),
};
});
}
renderCustomActions(props) {
if (Platform.OS === 'ios') {
return (
<CustomActions
{...props}
/>
);
}
const options = {
'Action 1': (props) => {
alert('option 1');
},
'Action 2': (props) => {
alert('option 2');
},
'Cancel': () => {},
};
return (
<Actions
{...props}
options={options}
/>
);
}
renderBubble(props) {
return (
<Bubble
{...props}
wrapperStyle={{
left: {
backgroundColor: '#f0f0f0',
}
}}
/>
);
}
renderSystemMessage(props) {
return (
<SystemMessage
{...props}
containerStyle={{
marginBottom: 15,
}}
textStyle={{
fontSize: 14,
}}
/>
);
}
renderCustomView(props) {
return (
<CustomView
{...props}
/>
);
}
renderFooter(props) {
if (this.state.typingText) {
return (
<View style={styles.footerContainer}>
<Text style={styles.footerText}>
{this.state.typingText}
</Text>
</View>
);
}
return null;
}
render() {
return (
<GiftedChat
messages={this.state.messages}
onSend={this.onSend}
loadEarlier={this.state.loadEarlier}
onLoadEarlier={this.onLoadEarlier}
isLoadingEarlier={this.state.isLoadingEarlier}
user={{
_id: 1, // sent messages should have same user._id
}}
renderActions={this.renderCustomActions}
renderBubble={this.renderBubble}
renderSystemMessage={this.renderSystemMessage}
renderCustomView={this.renderCustomView}
renderFooter={this.renderFooter}
/>
);
}
}
const styles = StyleSheet.create({
footerContainer: {
marginTop: 5,
marginLeft: 10,
marginRight: 10,
marginBottom: 10,
},
footerText: {
fontSize: 14,
color: '#aaa',
},
});
app.js navigator part
const Main = StackNavigator(
{
Post: {screen: PostScreen},
Signin: {screen: SigninScreen},
Signup: {screen: SignupScreen},
Forgetpass: {screen: ForgetpassScreen},
Drawer: {screen: Drawer},
Welcome: {screen: WelcomeScreen},
Messages: {screen: MessagesScreen},
},
{
initialRouteName: "Signin",
headerMode: "none",
},
);
Also MessagesScreen was imported in the app.js and implemented inside the react-navigation. As I said it worked yesterday perfectly. While now causes error.
It's possible that yesterday you installed the module without saving and today you did a fresh npm install so you no longer have it. Can you verify that 1) react-native-gifted-chat is listed as a dependency in package.json and 2) react-native-gifted-chat exists under node_modules directory?

Resources