I am getting the error 'Unable to resolve module 'module://#babel/runtime/helpers/interopRequireDefault.js' when I try to run the following code in Expo Snack
Below is my code for HomeScreen.js
import { StyleSheet, Text, View, FlatList } from "react-native";
import axios from "axios";
import { useState, useEffect } from "react";
export default function HomeScreen() {
const [cycles, setCycles] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const { data: response } = await axios.get(
"URL"
);
setCycles(response);
} catch (error) {
console.error(error.message);
}
};
fetchData();
}, []);
return (
<View style={styles.container}>
{/* <Text> {JSON.stringify(cycles[0])} </Text> */}
<FlatList
data={cycles}
renderItem={(
{ item } //this part will iterate over every item in the array and return a listItem
) => (
<Text>
{new Date(item.startDate).toLocaleDateString("us-EN")} -{" "}
{new Date(item.endDate).toLocaleDateString("us-EN")}{" "}
</Text>
)}
/>
<Text>Hello</Text>
</View>
);
}
And below is App.js
import { StyleSheet, Text, View, FlatList } from "react-native";
import axios from "axios";
import { useState, useEffect } from "react";
import HomeScreen from "./screens/HomeScreen";
import { NavigationContainer } from "#react-navigation/native";
import { createNativeStackNavigator } from "#react-navigation/stack";
const Stack = createNativeStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
name="Home"
component={HomeScreen}
options={{ title: "Welcome" }}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
Package.json file
{
"dependencies": {
"react-native-paper": "4.9.2",
"#expo/vector-icons": "^13.0.0",
"expo-constants": "~13.2.4",
"axios": "*",
"#react-navigation/stack": "*",
"#react-navigation/native": "6.0.0",
"react-native-gesture-handler": "~2.5.0",
"react-native-safe-area-context": "4.3.1",
"react-native-screens": "~3.15.0"
}
}
From one of the questions I found Unable to resolve module `#babel/runtime/helpers/interopRequireDefault`, I tried adding babel and it has not worked.(ie it throws another error as below)
Thanks for any help!
Downgrade axios to 0.27.2 to align with Expo built-in #babel/runtime version.
Related
I'm learning react native but I'm having difficulty with navigation, it's returning the error that navigation has not been initialized yet.
I looked for some tutorials, I tried some other ways, I went to the react native navigation documentation and, incredible as it may seem, it's the same as in the documentation... not even the GPT chat haha it didn't help me.
Can someone with experience in react native give me a light?
app.tsx:
import { NavigationContainer } from '#react-navigation/native';
import { createAppContainer } from 'react-navigation';
import StackNavigator from './app/index/navigator';
const AppContainer = createAppContainer(StackNavigator);
const App = () => {
return (
<NavigationContainer>
<AppContainer />
</NavigationContainer>
);
}
export default App;
navigator.tsx?
import { createStackNavigator } from 'react-navigation-stack';
import Index from '.';
import AddNewGrocery from '../components/addNewGrocery'
const StackNavigator = createStackNavigator({
home: { screen: Index, navigationOptions: { headerShown: false } },
addNewGrocery: { screen: AddNewGrocery, navigationOptions: { headerShown: false } },
});
export default StackNavigator;
index.tsx:
const Index = () => {
return (
<View style={styles.container}>
<Text style={styles.title}>Gestão de Compras</Text>
<LastFiveGrocery />
<MonthAverageSpend />
<TotalSpend />
<AddButton />
<StatusBar
translucent={false}
backgroundColor={'rgba(43, 43, 43, 1)'}
barStyle='light-content' />
</View>
);
}
AddButton.tsx:
import React from 'react';
import { StyleSheet, View, TouchableOpacity } from 'react-native';
import { Ionicons } from '#expo/vector-icons';
import { useNavigation } from '#react-navigation/native';
const AddButton = () => {
const navigation = useNavigation();
const handleAddButtonPress = () => {
navigation.navigate('addNewGrocery' as never);
}
return (
<TouchableOpacity style={styles.addButtonContainer} onPress={handleAddButtonPress}>
<View style={styles.addButton}>
<Ionicons name="ios-add" size={36} color="white" />
</View>
</TouchableOpacity>
);
}
I already tried to use it this way:
AddButton:
const { navigate } = useNavigation<StackNavigationProp<ParamListBase>>();
const handleAddButtonPress = () => {
navigate('addNewGrocery');
}
I've also tried using it this way:
navigator:
const StackNavigator = createAppContainer(createStackNavigator({
Home: { screen: Index },
addNewGrocery: AddNewGrocery,
}));
app.tsx:
import StackNavigator from './app/index/navigator';
const App = () => {
return (
<StackNavigator />
);
}
export default App;
You are using 2 different navigation library in simultaneously:
#react-navigation
react-navigation
Remove react-navigation and refactor the App.js file as below:
import { NavigationContainer } from '#react-navigation/native';
import StackNavigator from './app/index/navigator';
const App = () => {
return (
<NavigationContainer>
<StackNavigator />
</NavigationContainer>
);
}
export default App
StackNavigator should be implemented as per documentation -
https://reactnavigation.org/docs/stack-navigator/#api-definition
I have an issue with Stack.Navigator on Android. It just doesn't work by some strange reason.
There is simple code:
import React from 'react';
import {createNativeStackNavigator} from '#react-navigation/native-stack';
import {ROUTES} from '../../constants/routes';
import {AuthScreen, LoginScreen, RegisterScreen} from './screens';
export const Unauthorized = () => {
const Stack = createNativeStackNavigator();
return (
<Stack.Navigator
initialRouteName={ROUTES.ROUTE_AUTH}
screenOptions={{headerShown: false}}>
<Stack.Screen name={ROUTES.ROUTE_AUTH} component={AuthScreen} />
<Stack.Screen name={ROUTES.ROUTE_LOGIN} component={LoginScreen} />
<Stack.Screen name={ROUTES.ROUTE_REGISTER} component={RegisterScreen} />
</Stack.Navigator>
);
};
Looks simple. AuthScreen component also is simple:
import React from 'react';
import {SafeAreaView, StyleSheet, Text} from 'react-native';
export const AuthScreen = () => {
return (
<SafeAreaView>
<Text style={styles.text}>Auth screen</Text>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
text: {
color: 'red',
},
});
There is a App.tsx:
import 'react-native-gesture-handler';
import React from 'react';
import {SafeAreaView, StatusBar, useColorScheme} from 'react-native';
import {Colors} from 'react-native/Libraries/NewAppScreen';
import {ApolloProvider} from '#apollo/client';
import client from './src/apollo';
import {SplashScreen} from './src/screens';
const App = () => {
const isDarkMode = useColorScheme() === 'dark';
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<ApolloProvider client={client}>
<SafeAreaView style={backgroundStyle}>
<SplashScreen />
<StatusBar backgroundColor="white" barStyle="dark-content" />
</SafeAreaView>
</ApolloProvider>
);
};
export default App;
But screen is empty when app is Running.
But if I remove Stack.Navigator at all then the content gets visible
Any notes with dependencies or MainActivity I have done.
There is deps:
"#apollo/client": "^3.7.1",
"#react-navigation/native": "^6.0.6",
"#react-navigation/native-stack": "^6.2.5",
"#react-navigation/stack": "^6.0.11",
"graphql": "^16.6.0",
"react": "18.1.0",
"react-hook-form": "^7.39.1",
"react-native": "0.70.4",
"react-native-bootsplash": "^4.3.3",
"react-native-gesture-handler": "^2.8.0",
"react-native-mmkv-storage": "^0.8.0",
"react-native-safe-area-context": "^4.4.1",
"react-native-screens": "^3.10.0"
I spent 4 hours and I have no more ideas how to get Stask.Navigator to show content....
I tried to use
import {createStackNavigator} from '#react-navigation/stack'
const Stack = createStackNavigator()
instead of createNativeStackNavigator
I tried to change versions. Nothing helped.
give flex:1 style to SafeAreaView in App.js
Im following this tutorial https://github.com/nathvarun/Expo-Google-Login-Firebase and below is my code. However the signInWithGoogleAsync() function is not getting invoked it seems. Clicking the button does nothing. Could it be because of stack Navigator?
There is no issue with firebase as email login is working
Below is my LoginScreen.js
import { useNavigation } from '#react-navigation/core'
import React, { useEffect, useState, Component } from 'react'
import { Button, KeyboardAvoidingView, StyleSheet, Text,TextInput, TouchableOpacity, View } from 'react-native'
import { auth } from '../firebase'
import * as GoogleSignIn from 'expo-google-sign-in';
class LoginScreen extends Component {
signInWithGoogleAsync = async() => {
try {
const result = await Google.logInAsync({
behavior:'web',
iosClientId: 'lorem ipsum',
scopes: ['profile', 'email'],
});
if (result.type === 'success') {
return result.accessToken;
} else {
return { cancelled: true };
}
} catch (e) {
return { error: true };
}
};
render(){
return (
<KeyboardAvoidingView
style={styles.container}
behavior="padding"
>
<View style={styles.inputContainer}>
<Button
title='sign'
onPress={()=>this.signInWithGoogleAsync()} />
</View>
</KeyboardAvoidingView>
);
}
}
export default LoginScreen
here's the App.js:
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import LoginScreen from './screens/LoginScreen';
import HomeScreen from './screens/HomeScreen';
import * as firebase from "firebase/compat";
const Stack = createNativeStackNavigator();
export default class App extends React.Component {
render(){
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen options={{ headerShown: false }} name="Login" component={LoginScreen} />
<Stack.Screen name="Home" component={HomeScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
registerRootComponent(App);
You are importing everythin as GoogleSignIn and then below doing await Google.logInAsync so you'd have to change that to await GoogleSignIn.loadInAsync. 9th line
Also, look at the docs, it doesn't look like logInAsync is a function https://docs.expo.dev/versions/latest/sdk/google-sign-in/
expo-google-sign-in has been now deprecated. You'll have to use expo-auth-session
I am a new member of React Native and i stuck :)
I need to login to the main screen(Anaekran.js) with the correct mail and password. I get mail and password information from API.
When I press the button(MyButton), I expect the code to check the mail and password and redirect to the main screen(Anaekran.js) if it is correct, but nothing happens. I couldn't find the problem or problems. l really appreciate any help you can provide. I will return immidately for your answers and questions.
I used the router flux for navigating process. I don't share the Anaekran.js because i don't think we need Anaekran.js right now.
Some method,file names are Turkish.
This is LoginSayfasi.js (login page).
import React, {Component} from 'react';
import {View,Alert} from 'react-native';
import Input from '../components/Input';
import MyButton from '../components/MyButton';
import {Actions} from 'react-native-router-flux';
import {
isLogin
} from '../components/Index';
import { serializeKey, setSessionTicket } from '../components/Index'
export default class LoginSayfasi extends Component {
constructor(props) {
super(props);
this.isLoginControl();
this.state = {
mail: '',
password: '',
};
}
async isLoginControl() {
var present = this;
isLogin().then((res) => {
if (res)
Actions.Anaekran({type: 'reset'});
else
Actions.LoginSayfasi({type: 'reset'});
})
}
Giris() {
var name = this.state.mail;
var pass = this.state.password;
if (name == "" || pass == "") {
Alert.alert("You have to fill ");
} else {
fetch('192.168.1.14/rest/signin', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: serializeKey({
mail: name,
password: pass
})
})
.then((res) => res.json())
.then((res) => {
if (res.session_ticket)
setSessionTicket(String(res.session_ticket));
if (res.status != -1)
Actions.Anaekran({type: 'reset'});
else
Alert.alert("User could not be verified");
})
.catch((err) => {
Alert.alert("There is a problem here! " + err);
})
}
}
render() {
return (
<View>
<Input
placeholder="Mail"
autoCapitalize="none"
onSubmitEditing={() => this.passwordInput.focus()}
onChangeText={(value) => this.setState({mail : value})}
value={this.state.mail}
keyboardType={'email-address'}
/>
<Input
placeholder="Password"
secureTextEntry={true}
inputRef={input => (this.passwordInput = input)}
onChangeText={(value) => this.setState({password : value})}
value={this.state.password}
/>
<MyButton
textColor={'#f1f1f1'}
text={'Sign In'}
bgColor={'#0065e0'}
onPress={this.Giris.bind(this)}
/>
</View>
);
}
}
Login.js
import React, {Component} from 'react';
import {
StyleSheet,
View,
Text,
KeyboardAvoidingView
} from 'react-native';
import LoginSayfasi from '../ekranlar/LoginSayfasi';
export default class Login extends Component {
render() {
return (
<View style={styles.container}>
<View style={styles.headBackground} />
<KeyboardAvoidingView behavior={'position'}>
<View>
<Text style={styles.text1}>BLA BLA</Text>
<Text style={styles.text2}>BLAAAA</Text>
</View>
<View style={styles.loginArea}>
<LoginSayfasi />
</View>
</KeyboardAvoidingView>
</View>
);
}
}
const styles = StyleSheet.create({
// STYLES //
});
components/Index.js
import AsyncStorage from '#react-native-community/async-storage';
export function serializeKey(data) {
var formBody = [];
for (var property in data) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(data[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");
return formBody;
}
export async function isLogin() {
var session = await AsyncStorage.getItem("session_ticket");
if (session != null)
return true;
return false;
}
export async function setSessionTicket(ticket) {
AsyncStorage.setItem("session_ticket", ticket);
}
components/Input.js
import React, {Component} from 'react';
import {StyleSheet, TextInput, View} from 'react-native';
export default class Input extends Component {
state = {
text: '',
};
render() {
return (
<View>
<TextInput
{...this.props}
placeholderTextColor="#ddd"
style={styles.input}
value={this.state.text}
ref={this.props.inputRef}
onChangeText={text => this.setState({text})}
/>
</View>
);
}
}
const styles = StyleSheet.create({
// STYLES //
});
components/MyButton.js
import React, {Component} from 'react';
import {StyleSheet, Text, TouchableOpacity} from 'react-native';
import PropTypes from 'prop-types';
export default class MyButton extends Component {
render() {
return (
<TouchableOpacity
style={[styles.button,
{backgroundColor: this.props.bgColor}]}>
<Text style={{color: this.props.textColor}}>{this.props.text}</Text>
</TouchableOpacity>
);
}
}
MyButton.propTypes = {
text: PropTypes.string.isRequired,
bgColor: PropTypes.string,
textColor: PropTypes.string,
};
const styles = StyleSheet.create({
// STYLES //
});
package.json
{
"name": "bookreen",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"#react-native-community/async-storage": "^1.7.1",
"mobx": "^5.15.1",
"mobx-react": "^6.1.4",
"react": "16.9.0",
"react-native": "0.61.5",
"react-native-gesture-handler": "^1.5.2",
"react-native-reanimated": "^1.4.0",
"react-native-router-flux": "^4.0.6",
"react-native-screens": "^1.0.0-alpha.23",
"react-navigation": "^4.0.10",
"react-navigation-stack": "^1.10.3"
},
"devDependencies": {
"#babel/core": "7.7.5",
"#babel/plugin-proposal-decorators": "^7.7.4",
"#babel/runtime": "7.7.6",
"#react-native-community/eslint-config": "0.0.5",
"babel-jest": "24.9.0",
"eslint": "6.7.2",
"jest": "24.9.0",
"metro-react-native-babel-preset": "^0.56.3",
"react-test-renderer": "16.9.0"
},
"jest": {
"preset": "react-native"
}
}
App.js (Routes)
import React, { Component } from 'react';
import {
AppRegistry
} from 'react-native';
import {Actions, Scene, Router} from 'react-native-router-flux';
import Anaekran from './ekranlar/Anaekran';
import MahalDetay from './ekranlar/MahalDetay';
import ToplantiList from './ekranlar/ToplantiList';
import Login from './ekranlar/Login';
export default class LoginApp extends Component {
render() {
const scenes = Actions.create(
<Scene key="root" hideNavBar={true}>
<Scene key="Login" component={Login}/>
<Scene key="Anaekran" component={Anaekran}/>
<Scene key="MahalDetay" component={MahalDetay}/>
<Scene key="ToplantiList" component={ToplantiList}/>
</Scene>
);
return <Router scenes={scenes}/>
}
}
AppRegistry.registerComponent('App', () => App);
You are passing onPress property into MyButton component but you are not handling that property inside MyButton.js. That's why your Giris function is not being executed at all. You should handle that property inside MyButton and pass that prop to TouchableOpacity like(notice the line that starts with onPress):
<TouchableOpacity
style={[styles.button,
{backgroundColor: this.props.bgColor}]}
onPress={this.props.onPress}>
<Text style={{color: this.props.textColor}}>{this.props.text}</Text>
</TouchableOpacity>
I have looked at similar questions but none of the solutions seem to be working for me and this has stumped me for 2 days now.
The error seems to be coming from passing this.props.navigate through to exerciseList.js however everything I have tried doesn't work. So any advice would be very much appreciated. The error occurs when I click through exerciseList.js to the individually rendered .
Error message screenshot here
Error Message:
undefined is not a function (evaluating '_this2.props.navigate('Exercises', { exerciseName:ex})')
package.json
"dependencies": {
"prop-types": "^15.6.2",
"react": "16.6.3",
"react-native": "0.58.3",
"react-native-elements": "^1.0.0",
"react-native-gesture-handler": "^1.0.15",
"react-native-vector-icons": "^6.3.0",
"react-navigation": "^3.2.3"
},
router.js:
import React from 'react';
import {
createAppContainer,
createMaterialTopTabNavigator,
createStackNavigator} from 'react-navigation';
import { Icon } from 'react-native-elements';
import Home from '../home'
import ExercisePage from '../exercises/exercise';
import ExerciseList from '../exercise-list/exercise-list'
import CreateExerciseList from '../exercise-list/createListPage';
export const Route = createStackNavigator(
{
Home: { screen: Home },
Exercises: { screen: ExercisePage },
CreateList: { screen: CreateExerciseList },
ExerciseList: { screen: ExerciseList },
},
{
initialRouteName: 'Home'
}
);
const AppContainer = createAppContainer(Route);
export default AppContainer;
home.js:
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, Button, TouchableNativeFeedback } from 'react-native';
import Record from './exercises/reps';
import ExerciseList from './exercise-list/exercise-list'
import ExerciseListItem from './exercise-list/exerciseListItem'
import CreateExerciseList from './exercise-list/createListPage';
export default class Home extends Component {
render() {
return (
<View style={styles.container}>
<CreateExerciseList navigate={this.props.navigation.navigate}/>
</View>
);
}
}
createListPage.js:
import React, { Component } from 'react'
import { View, Text, Button, StyleSheet, TouchableNativeFeedback, ScrollView } from 'react-native'
import ExerciseListItem from './exerciseListItem';
export default class CreateExerciseList extends Component {
constructor(props) {
super(props)
this.state = {
workoutList: [
{
"name": "Leg Day",
"exercises": [
"Benchpress",
"Squat",
"Lateral extensions",
"Bicep curls",
"Tricep extensions",
"Shrugs"
]
},
{
"name": "Arm Day",
"exercises": [
"Jumping Jacks",
"Hack squats",
"Tricep curls",
"Flying"
]
}
]
}
}
render() {
const navigate = this.props.navigate
return (
<ScrollView>
<View>
<Text style={styles.header}>Create new list:</Text>
</View>
<View >
<Button style={styles.buttonNew} title='Create new list +'></Button>
</View>
<View style={styles.listContainer}>
{this.state.workoutList.map((workout) => {
return <TouchableNativeFeedback navigate={navigate} key={Date.now()} onPress={() => navigate('ExerciseList', {
title: workout.name,
exercises: workout.exercises,
})}>
<View>
<Text style={styles.listItem}>{workout.name}</Text>
</View>
</TouchableNativeFeedback>
})}
</View>
</ScrollView>
)
}
}
exerciseList.js:
import React, { Component } from 'react'
import { Text, View, StyleSheet, ScrollView } from 'react-native'
import ExerciseListItem from './exerciseListItem'
export class ExerciseList extends Component {
constructor(props) {
super(props)
this.state = {
exercises: []
}
}
componentDidMount() {
const { navigation } = this.props;
const title = navigation.getParam('title', 'no title available');
const exercises = navigation.getParam('exercises', 'no exercises found');
this.setState({
title: title,
exercises: exercises,
})
}
render() {
const navigate = this.props.navigate
return (
<View style={styles.scrollView}>
<View>
<Text style={styles.header}>{this.state.title}</Text>
</View>
<ScrollView style={styles.scrollView}>
{this.state.exercises.map((ex) => {
return <ExerciseListItem style={styles.listItem} exerciseName={ex} key={Date.now()} onPress={(ex) => navigate('Exercises', {exerciseName: ex})} />
})}
</ScrollView>
</View>
)
}
}
On your exerciseList.js, try importing this:
import { withNavigation } from 'react-navigation';
What withNavigation does is it provides the navigation prop directly to the component, without the need to pass it through props. You can read more about it here:
https://reactnavigation.org/docs/en/connecting-navigation-prop.html
Also, as Atin Singh mentioned on the comments, you should pass the navigation props like this: navigation = {this.props.navigation} and not as you are passing on your HOC. Then you'll just access the props on the child component like this: this.props.navigation.