React Native cannot find module - javascript

I am trying to build a basic notification app that uses the react-native-background-task module. For some reasons it gives this error: Cannot read properties of undefined (reading 'schedule')
Below is the code:
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import BackgroundTask from 'react-native-background-task';
// import { Notifications, Permissions, Constants } from 'expo';
import * as Notifications from 'expo-notifications';
import * as Permissions from 'expo-permissions';
import React, { useEffect } from 'react'
console.log("object")
BackgroundTask.define(async () => {
console.log("bgtask")
// if time is 12pm, fire off a request with axios to fetch the pills info
// Notification configuration object
const localNotification = {
title: text,
body: 'msg',
data: data,
ios: {
sound: true
}
}
// trigger notification, note that on ios if the app is open(in foreground) the notification will not show so you will need to find some ways to handling it which is discribed here https://docs.expo.io/versions/latest/guides/push-notifications
Notifications
.presentLocalNotificationAsync(localNotification)
.catch((err) => {
console.log(err)
})
BackgroundTask.finish()
})
export default function App() {
useEffect(() => {
console.log("uef")
const componentDidMount = async () => {
// allows the app to recieve notifications (permission stuff)
console.log("cdm")
registerForPushNotificationsAsync().then(() => {
console.log("bg sche")
BackgroundTask.schedule()
}).catch((e) => {
console.log("err")
console.log(e)
});
}
componentDidMount()
}, []);
const registerForPushNotificationsAsync = async () => {
console.log("reg")
const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
if (status !== 'granted') {
console.log("permission not granted")
return;
}
console.log("permission granted")
let deviceToken = await Notifications.getExpoPushTokenAsync()
}
return (
<View style={styles.container}>
<Text>Open up App.js \o start working on your app!</Text>
<StatusBar style="auto" />
</View>
);
}
The problem comes when I do the BackgroundTask.schedule() function. It says in the error that BackgroundTask is undefined. I know for a fact that all the other functions worked fine because the console.logs all get printed right until "bg sche" and then it goes and print "err" in the catch block.
I also tried to use ctrl + click on the package name that should bring me to source where this BackgroundTask object is exported but it doesn't work like it usually does for other modules. So I think for some reasons the module can't be found but I have already installed it and it is in my package.json file and I see it in my node_modules folder.

Related

React Native says function doesn't exist when trying context for routing and auth

This is my first real mobile app and when I am trying to implement auth and routing I am running into some issues - both error message and I am guessing functional too
My app currently has two stacks, an auth stack, and a drawer stack. I have the auth stack as the default stack and want to display the drawer stack if the user is logged in. If they are logged out show them the auth stack till they login.
I have this line of code in my root stack navigator
{ auth ? <Stack.Screen name="Auth" component={AuthStack} />:<Stack.Screen name="Drawer" component={DrawerStack} />}
Above my stack navigator I have this line
const { auth } = checkAuth()
Which is imported using - correct file path
import { AuthProvider, checkAuth } from '../context/AuthContext'
The base code from that import is below
const AuthProvider = ({ children }) => {
const [auth, setAuth] = useState(null);
const checkAuth = () => {
try {
const authData = globalStorage.getString('accessToken')
if(authData !== null && authData !== undefined) {
setAuth(authData)
}
} catch(e) {
console.error(e)
}
}
const removeAuth = () => {...};
const setAuthState = data => {
try {
console.log('setAuthState Data: ', data)
globalStorage.set('accessToken', data)
setAuth(data);
} catch (err) {
console.error(err);
}
};
useEffect(() => {
checkAuth();
}, []);
return (
<AuthContext.Provider value={{ auth, setAuthState, removeAuth}}>
{children}
</AuthContext.Provider>
);
};
The error message I am seeing in the iOS simulator is that checkAuth is not a function. I am not sure why it isn't when I am doing the import. I tried adding the AuthProvider as a prepend but no luck. I am sure this is a simple React thing but I'm not sure as I don't normally code this way when I do Node.js work.
Edit
import { AuthProvider, checkAuth } from '../context/AuthContext'
...
const AppNavigation = () => {
return (
<AuthProvider> <-- Error on this line
<RootNavigator />
</AuthProvider>
);
};
...
Error message
undefined is not an object (evaluating '_react.React.createElement')
checkAuth is scoped to AuthProvider. You'll want to include it in the value prop of AuthContext.Provider if you want make it available to consumers of your AuthContext, but I'd imagine you'll just want to use auth which is already provided to consumers.
Here is some info on the useContext hook where you can access those properties. https://reactjs.org/docs/hooks-reference.html#usecontext

React Native - App stuck on splash screen after launch released iOS

I uploaded my app to Play Store without any problem. However, when I tried to install the App Store, the application was rejected and I received the following message.
Guideline 2.1 - Performance - App Completeness
We discovered one or more bugs in your app. Specifically, the app
displayed only a splash screen.
Review device details:
Device type: iPhone
OS version: iOS 15.1
I tried the application both on the simulator and on the real device with testflight. But I have never encountered such a problem. Does anyone know the reason or are having the same problem?
I've done almost the same application before. The only difference is that I add anonymousSignIn() in this app. Is this what broke the app or is there something else? Here my splash screen codes:
import React, { useEffect } from 'react'
import AsyncStorage from "#react-native-async-storage/async-storage"
import { View } from 'react-native'
import AppIcon from '../../assets/svgs/app-icon.svg'
import styles from './styles/SplashStyles'
import { RemoteConfig } from '../../api/RemoteConfig'
import { getData } from '../../api/RealtimeDb'
import { NotificationUtil } from "../../utils/NotificationUtil"
import { InitializeUtil } from "../../utils/InitializeUtil"
import { pushNotification } from '../../api/PushNotification';
import { anonymousSignIn } from '../../api/Auth'
const remoteConfig = new RemoteConfig()
const notificationUtil = new NotificationUtil()
const initializeUtil = new InitializeUtil()
const Splash = ({ navigation }) => {
// asking user for notification permission (iOS)
function permission() {
notificationUtil.pushNotificationAPNsPermissions()
}
useEffect(() => {
async function splash() {
// fetches the remote config data from firebase
remoteConfig.init()
pushNotification()
//message to be shown in the alert
const message = remoteConfig.getAlertMessage().text
// alert before notification permission
await notificationUtil.alertBeforeNotificationPermission(
message,
permission
)
await anonymousSignIn()
getData()
.then(async (response) => {
const lastViewedWord = await AsyncStorage.getItem("lastViewedWord")
const page = await initializeUtil.getPageNameToVisit()
navigation.reset({
index: 0,
routes: [{
name: page, params: {
lastViewedWord: lastViewedWord,
allData: response,
}
}]
})
})
}
splash()
}, [])
return (
<View style={styles.container} >
<AppIcon
height='100%'
width='50%'
/>
</View >
)
}
export default Splash

How to access a function from React Functional Component in a Normal Javascript File?

Greetings Javascript Developers. I'm stuck in a complex situation now where I need to access a function inside one of my functinal components outside in a normal js file.
Ok So here's what I'm doing: This is my Authorizer.js functional Component.
import React, { createContext, useState, useEffect, useContext } from "react";
import SplashScreen from "react-native-splash-screen";
import { useStore } from "../config/Store";
import { useDatabase } from "../config/Persistence";
import { getSessionCredentials } from "../config/Persistence";
import NavigationDrawer from "./NavigationDrawer";
import AuthStacks from "./AuthStacks";
const AuthContext = createContext();
export const useAuthorization = () => useContext(AuthContext);
export function Authorizer() {
//TODO check whether user is already signed in or not.
const realm = useDatabase();
const { state, dispatch } = useStore();
const [isAuthorized, setAuthorization] = useState(false);
useEffect(() => {
VerifyCredentials();
}, []);
async function VerifyCredentials() {
//TODO Check from Async Storage?
var session = await getSessionCredentials();
console.log("saved session", session);
if (session) {
await DispatchShopData();
await setAuthorization(true);
} else {
await setAuthorization(false);
}
sleep(1000).then(() => {
SplashScreen.hide();
});
}
async function DispatchShopData() {
try {
let shop = await realm.objects("Shop");
await dispatch({ type: "UPDATE_SHOP_DETAILS", payload: shop[0] });
} catch (error) {
console.log("failed to retrieve shop object", error);
}
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
return (
<AuthContext.Provider value={{ setAuthorization }}>
{isAuthorized ? <NavigationDrawer /> : <AuthStacks />}
</AuthContext.Provider>
);
}
This component basically handles my Authentication Flow, whether to show the Navigation Drawer or the Login Screen. Now I have another simple javascript file ApiService.js which does not have any components, only simple js functions.
import Axios from "axios";
import { getAuthToken } from "../config/Persistence";
import { LogoutUser } from "../config/Persistence";
import { Alert } from "react-native";
const BASE_URL = "#########################";
/** Defined my Api Endpoints Here */
let service = Axios.create({
baseURL: BASE_URL,
timeout: 10000,
});
service.interceptors.response.use((response) => {
console.log("[API] response intercepted data", response.data.message);
if (!response.data.status && response.data.tokenExpired) {
//Auth token has Expired. Show user Alert for Session Expired & redirect to login screen.
Alert.alert(
"Your Session has Expired!",
"Don't worry though. You just need to login again & you're set.",
[
{
text: "Continue",
style: "default",
onPress: () => {
LogoutUser()
.then((success) => {
if (success) {
//TODO Find a way to Access this function from Authorizer.js Component.
//setAuthorization(false);
}
})
.catch((error) => {
console.log("failed to logout after session expiry", error);
});
},
},
]
);
}
return response;
});
/** Defined my other api functions called inside my other components */
function TestSampleApi() {
try {
return new Promise(async function (resolve, reject) {
const response = await service.get("https://jsonplaceholder.typicode.com/users");
if (response.data != null) {
resolve(response.data);
} else {
reject(response.status);
}
});
} catch (error) {
console.log("request error", error.message);
}
}
export {
TestSampleApi,
/** Exporting other api functions as well */
};
In my ApiService.js file, I've setup a response interceptors whose job is to catch the default auth token expired response and SignOut user immediately and take him to the Login Screen. Here's now where my issue comes.
In normal scenarios, where I need to access functions from one component inside another component, I can manage is using CreateContext() and useContent() hooks. However, how do I access the useState function setAuthorization in my Authorizer.js components in my ApiService.js file as a normal js function.
I only need to call setAuthorization(false) from my response interceptor block to make the user return to the Login Screen. Problem is idk how to access that state setter function. So any help would be greatly appreciated.

react native -expo: is there a way to print the location on phone's screen?

Is there a way to print something on my phone screen?
I tried to print the "location" on the screen when I got the location change.
In my example, I try to use the TaskManager of expo because I have to run some background service and I want to check if this method work or not while the app is killed.
This is my code :
import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
import * as TaskManager from 'expo-task-manager';
import * as Location from 'expo-location';
const LOCATION_TASK_NAME = 'background-location-task';
export default class Component extends React.Component {
onPress = async () => {
const { status } = await Location.requestPermissionsAsync();
if (status === 'granted') {
await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
accuracy: Location.Accuracy.Balanced,
});
}
};
render() {
return (
<TouchableOpacity
style={{alignItems: "center",paddingTop:100}}
onPress={this.onPress}>
<Text>Enable background location</Text>
</TouchableOpacity>
);
}
}
TaskManager.defineTask(LOCATION_TASK_NAME, ({ data, error }) => {
if (error) {
// Error occurred - check `error.message` for more details.
return;
}
if (data) {
const { locations } = data;
// do something with the locations captured in the background
// HERE I WANT TO PRINT THE "locations" INTO MY PHONE SCREEN
}
});

Requiring unknown module "111"

I want to retrieve data from localhost:4547
So, I have a function named loadText which is suppose to do so in this code :
import React, { useState } from 'react'
import { StyleSheet, View, Text, TouchableOpacity } from 'react-native'
import { TextInput } from 'react-native-gesture-handler'
import { response } from 'express'
export default function Home(props) {
const { navigation } = props
return (
<View>
<Text>Login Screen</Text>
<Text>{loadText}</Text>
</View>
)
function loadText(){
fetch('http://192.168.1.14:4547/')
.then((response) => response.json())
.then((responseJson) => {
return (
alert(JSON.stringfy(responseJson))
);
})
.catch((error) => {
alert(JSON.stringfy(error));
});
}
}
PROBLEM: I receive the following error on my iphone : . Any idea on what module "111" is?
Additional info : Here are all my packages I have installed :
Try closing the Metro blunder, as the error says (The terminal or cmd that has the green loading bars, press cntrl + shift + c)
then, try again with npm start --reset-cache on your project folder. If this does'nt work, try with sudo, if you're on linux.

Categories

Resources