can someone please help me troubleshoot?
I am trying to search through a local JSON file and return the relevant data. My JSON file contains a restaurant name and restaurant type.
I don't understand where the issue may be coming from. When I comment out ListHeadComponent={this.renderHeader}, there is no error; however, nothing will display if I comment that out.
The issue I am getting is:
Invariant Violation: Invariant Violation: Tried to get frame for out of range index NaN
This error is located at:
in VirtualizedList (at FlatList.js:662)
in FlatList (at SearchScreen.js:75)
in RCTView (at View.js:44)
in SearchScreen (created by SceneView)
in SceneView (at StackViewLayout.js:795)
in RCTView (at View.js:44)
in AnimatedComponent (at StackViewCard.js:69)
in RCTView (at View.js:44)
in AnimatedComponent (at screens.native.js:59)
in Screen (at StackViewCard.js:57)
in Card (at createPointerEventsContainer.js:27)
in Container (at StackViewLayout.js:860)
in RCTView (at View.js:44)
in ScreenContainer (at StackViewLayout.js:311)
in RCTView (at View.js:44)
in AnimatedComponent (at StackViewLayout.js:307)
in Handler (at StackViewLayout.js:300)
in StackViewLayout (at withOrientation.js:30)
in withOrientation (at StackView.js:79)
in RCTView (at View.js:44)
in Transitioner (at StackView.js:22)
in StackView (created by Navigator)
in Navigator (at createKeyboardAwareNavigator.js:12)
in KeyboardAwareNavigator (created by SceneView)
in SceneView (at createTabNavigator.js:39)
in RCTView (at View.js:44)
in RCTView (at View.js:44)
in ResourceSavingScene (at createBottomTabNavigator.js:113)
in RCTView (at View.js:44)
in ScreenContainer (at createBottomTabNavigator.js:103)
in RCTView (at View.js:44)
in TabNavigationView (at createTabNavigator.js:197)
in NavigationView (created by Navigator)
in Navigator (created by SceneView)
in SceneView (created by SwitchView)
in SwitchView (created by Navigator)
in Navigator (at createAppContainer.js:388)
in NavigationContainer (at App.js:24)
in RCTView (at View.js:44)
in App (at withExpoRoot.js:22)
in RootErrorBoundary (at withExpoRoot.js:21)
in ExpoRootComponent (at renderApplication.js:34)
in RCTView (at View.js:44)
in RCTView (at View.js:44)
in AppContainer (at renderApplication.js:33)
This error is located at:
in NavigationContainer (at App.js:24)
in RCTView (at View.js:44)
in App (at withExpoRoot.js:22)
in RootErrorBoundary (at withExpoRoot.js:21)
in ExpoRootComponent (at renderApplication.js:34)
in RCTView (at View.js:44)
in RCTView (at View.js:44)
in AppContainer (at renderApplication.js:33)
The code in my .js file is:
import React from 'react';
import { ExpoConfigView } from '#expo/samples';
import { View, Text, FlatList, ActivityIndicator} from 'react-native';
import { SearchBar } from 'react-native-elements';
import restaurantList from '../assets/files/search.json';
export default class SearchScreen extends React.Component {
static navigationOptions = {
title: 'Search for Restaurants',
};
constructor() {
super();
this.state = {
loading: false,
data: {restaurantList},
error: null,
};
this.arrayholder = [];
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: '86%',
backgroundColor: '#CED0CE',
marginLeft: '14%',
}}
/>
);
};
searchFilterFunction = text =>{
this.setState({
value: text,
});
const newData = this.arrayholder.filter(item => {
const itemData = `${item.name.toUpperCase()}
${item.type.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
})
this.setState({
data: newData,
});
};
renderHeader = () => {
return (
<SearchBar
placeholder="Type..."
value={this.state.value}
onChange={text => this.searchFilterFunction(text)}
/>
);
};
render() {
if (this.state.loading) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<ActivityIndicator />
</View>
);
}
return (
<View>
<FlatList
data={this.state.data}
renderItem={({ item }) => (
<Text>{item.name} {item.type}</Text>
)}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
/>
</View>
);
}
}
Here is my json file
[
{
"name": "Shake Shack",
"type":"american"
},
{
"name": "BonChon Chicken",
"type": "korean"
},
{
"name": "Starbucks",
"type:": "cafe"
}
]
This is a really good start. However, there are a couple of issues with your code. So let's go through it and see where we can make some improvements.
Constructor
Firstly in your constructor you are making the data an object rather than array. FlatLists do not work with objects they work with arrays so this is going to immediately cause you problems. You really need to remove the {} from around the restaurantList.
constructor() {
super();
this.state = {
loading: false,
data: {restaurantList}, // You shouldn't have {} around the restaurantList
error: null,
};
this.arrayholder = []; // we also don't need this
}
You should update your constructor to this
constructor (props) {
super(props);
this.state = {
loading: false,
data: restaurantList, // notice we have no {} around restaurantList
error: null,
value: ''
};
}
renderHeader
In your renderHeader function you are using onChange rather than onChangeText. onChange returns an object, but you want the text that has been put into the search bar. You need to update your renderHeader function to be like this.
renderHeader = () => {
return (
<SearchBar
placeholder="Type..."
value={this.state.value}
onChangeText={text => this.searchFilterFunction(text)} // now we are using the correct function to capture the text
/>
);
};
searchFilterFunction
There are several issues with this function. Firstly you are looking at this.arrayholder which is empty. We don't actually need an additional array to hold the data as we can just use the restaurantList that we imported earlier. Secondly you are using indexOf on a string it is better to use includes.
searchFilterFunction = text => {
this.setState({
value: text
});
const newData = restaurantList.filter(item => {
const itemData = `${item.name.toUpperCase()} ${item.type.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.includes(textData); // this will return true if our itemData contains the textData
});
this.setState({
data: newData
});
};
FlatList
In your FlatList you should use the extraData prop as this will allow the FlatList to update when the underlying data changes. You should also add a keyExtractor.
<FlatList
keyExtractor={(item, index) => `${index}`}
extraData={this.state} // <- add this prop
data={this.state.data}
renderItem={({ item }) => (
<Text>{item.name} {item.type}</Text>
)}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
/>
Putting it all together
So if we put this all together, adding a mock of data so that we can check it works. We should get something like this.
// mock the data as you didn't provide an example
const restaurantList = [
{
type: 'Italian',
name: 'DiMaggio'
},
{
type: 'Greek',
name: 'Athena'
}
];
export default class SearchScreen extends React.Component {
static navigationOptions = {
title: 'Search for Restaurants'
};
constructor (props) {
super(props);
this.state = {
loading: false,
data: restaurantList,
error: null,
value: ''
};
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: '86%',
backgroundColor: '#CED0CE',
marginLeft: '14%'
}}
/>
);
};
searchFilterFunction = text => {
this.setState({
value: text
});
const newData = restaurantList.filter(item => {
const itemData = `${item.name.toUpperCase()} ${item.type.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.includes(textData);
});
this.setState({
data: newData
});
};
renderHeader = () => {
return (
<SearchBar
placeholder="Type..."
value={this.state.value}
onChangeText={text => this.searchFilterFunction(text)}
/>
);
};
render () {
if (this.state.loading) {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<ActivityIndicator />
</View>
);
} else {
return (
<View style={styles.container}>
<FlatList
keyExtractor={(item, index) => `${index}`}
extraData={this.state}
data={this.state.data}
renderItem={({ item }) => (
<Text>{item.name} {item.type}</Text>
)}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
/>
</View>
);
}
}
}
Snack
You can see it working at the following snack https://snack.expo.io/#andypandy/flatlist-with-search
Related
import React, { useCallback, useMemo, useRef } from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import BottomSheet, { BottomSheetFlatList } from "#gorhom/bottom-sheet";
export default function App() {
// hooks
const sheetRef = useRef<BottomSheet>(null);
// variables
const data = useMemo(
() =>
Array(50)
.fill(0)
.map((_, index) => `index-${index}`),
[]
);
const snapPoints = useMemo(() => ["25%", "50%", "90%"], []);
// callbacks
const handleSheetChange = useCallback((index) => {
console.log("handleSheetChange", index);
}, []);
const handleSnapPress = useCallback((index) => {
sheetRef.current?.snapToIndex(index);
}, []);
const handleClosePress = useCallback(() => {
sheetRef.current?.close();
}, []);
// render
const renderItem = useCallback(
({ item }) => (
<View style={styles.itemContainer}>
<Text>{item}</Text>
</View>
),
[]
);
return (
<View style={styles.container}>
<Button title="Snap To 90%" onPress={() => handleSnapPress(2)} />
<Button title="Snap To 50%" onPress={() => handleSnapPress(1)} />
<Button title="Snap To 25%" onPress={() => handleSnapPress(0)} />
<Button title="Close" onPress={() => handleClosePress()} />
<BottomSheet
ref={sheetRef}
snapPoints={snapPoints}
onChange={handleSheetChange}
>
<BottomSheetFlatList
data={data}
keyExtractor={(i) => i}
renderItem={renderItem}
contentContainerStyle={styles.contentContainer}
/>
</BottomSheet>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 200,
},
contentContainer: {
backgroundColor: "white",
},
itemContainer: {
padding: 6,
margin: 6,
backgroundColor: "#eee",
},
});
I am getting this error
Error: Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref
This error is located at:
in RCTView (created by View)
in View (created by App)
in App (created by withDevTools(App))
in withDevTools(App)
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in main(RootComponent)
i want to know where i have mistaken or is there any other steps need to be followed.
Try this:
const sheetRef = useRef<BottomSheet | null>(null);
Or
const sheetRef = useRef<BottomSheet>();
I have this in my React Native Code:
import React, {useState} from 'react';
import {View, StyleSheet} from 'react-native';
import {Text} from 'react-native-paper';
import {TextInput} from 'react-native-paper';
import AsyncStorage from '#react-native-community/async-storage';
import {Button} from 'react-native-paper';
export default function LoginScreen(props) {
const [userId, setUserId] = useState('');
const [loading, setLoading] = useState(false);
const onLogin = async () => {
setLoading(true);
try {
await AsyncStorage.setItem('userId', userId);
setLoading(false);
props.navigation.push('Call');
} catch (err) {
console.log('Error', err);
setLoading(false);
}
};
return (
<View style={styles.root}>
<View style={styles.content}>
<Text style={styles.heading}>Enter your id</Text>
<TextInput
label="Your ID"
onChangeText={text => setUserId(text)}
mode="outlined"
style={styles.input}
/>
<Button
mode="contained"
onPress={onLogin}
loading={loading}
style={styles.btn}
contentStyle={styles.btnContent}
disabled={userId.length === 0}>
Login
</Button>
</View>
</View>
);
}
const styles = StyleSheet.create({
root: {
backgroundColor: '#fff',
flex: 1,
// alignItems: 'center',
justifyContent: 'center',
},
content: {
// alignSelf: 'center',
paddingHorizontal: 20,
justifyContent: 'center',
},
heading: {
fontSize: 18,
marginBottom: 10,
fontWeight: '600',
},
input: {
height: 60,
marginBottom: 10,
},
btn: {
height: 60,
alignItems: 'stretch',
justifyContent: 'center',
fontSize: 18,
},
btnContent: {
alignItems: 'center',
justifyContent: 'center',
height: 60,
},
});
And this to call the peer:
import React, {useEffect, useState, useCallback} from 'react';
import {View, StyleSheet, Alert} from 'react-native';
import {Text} from 'react-native-paper';
import {Button} from 'react-native-paper';
import AsyncStorage from '#react-native-community/async-storage';
import {TextInput} from 'react-native-paper';
import {useFocusEffect} from '#react-navigation/native';
import InCallManager from 'react-native-incall-manager';
import {
RTCPeerConnection,
RTCIceCandidate,
RTCSessionDescription,
RTCView,
MediaStream,
MediaStreamTrack,
mediaDevices,
registerGlobals,
Permissions,
} from 'react-native-webrtc';
export default function CallScreen({navigation, ...props}) {
let name;
let connectedUser;
const [userId, setUserId] = useState('');
const [socketActive, setSocketActive] = useState(false);
const [calling, setCalling] = useState(false);
// Video Scrs
const [localStream, setLocalStream] = useState({toURL: () => null});
const [remoteStream, setRemoteStream] = useState({toURL: () => null});
const [conn, setConn] = useState(new WebSocket('ws://localhost:8080'));
const [yourConn, setYourConn] = useState(
//change the config as you need
new RTCPeerConnection({
iceServers: [
{
urls: 'stun:stun.l.google.com:19302',
}, {
urls: 'stun:stun1.l.google.com:19302',
}, {
urls: 'stun:stun2.l.google.com:19302',
}
],
}),
);
const permissionCheck = async () => {
const { status } = await Permissions.askAsync(Permissions.CAMERA);
};
const [offer, setOffer] = useState(null);
const [callToUsername, setCallToUsername] = useState(null);
useFocusEffect(
useCallback(() => {
AsyncStorage.getItem('userId').then(id => {
console.log(id);
if (id) {
setUserId(id);
} else {
setUserId('');
navigation.push('Login');
}
});
}, [userId]),
);
useEffect(() => {
navigation.setOptions({
title: 'Your ID - ' + userId,
headerRight: () => (
<Button mode="text" onPress={onLogout} style={{paddingRight: 10}}>
Logout
</Button>
),
});
}, [userId]);
/**
* Calling Stuff
*/
useEffect(() => {
if (socketActive && userId.length > 0) {
try {
InCallManager.start({media: 'audio'});
InCallManager.setForceSpeakerphoneOn(true);
InCallManager.setSpeakerphoneOn(true);
} catch (err) {
console.log('InApp Caller ---------------------->', err);
}
console.log(InCallManager);
send({
type: 'login',
name: userId,
});
}
}, [socketActive, userId]);
const onLogin = () => {};
useEffect(() => {
/**
*
* Sockets Signalling
*/
permissionCheck();
conn.onopen = () => {
console.log('Connected to the signaling server');
setSocketActive(true);
};
//when we got a message from a signaling server
conn.onmessage = msg => {
let data;
if (msg.data === 'Hello world') {
data = {};
} else {
data = JSON.parse(msg.data);
console.log('Data --------------------->', data);
switch (data.type) {
case 'login':
console.log('Login');
break;
//when somebody wants to call us
case 'offer':
handleOffer(data.offer, data.name);
console.log('Offer');
break;
case 'answer':
handleAnswer(data.answer);
console.log('Answer');
break;
//when a remote peer sends an ice candidate to us
case 'candidate':
handleCandidate(data.candidate);
console.log('Candidate');
break;
case 'leave':
handleLeave();
console.log('Leave');
break;
default:
break;
}
}
};
conn.onerror = function(err) {
console.log('Got error', err);
};
/**
* Socjket Signalling Ends
*/
let isFront = false;
mediaDevices.enumerateDevices().then(sourceInfos => {
let videoSourceId;
for (let i = 0; i < sourceInfos.length; i++) {
const sourceInfo = sourceInfos[i];
if (
sourceInfo.kind == 'videoinput' &&
sourceInfo.facing == (isFront ? 'front' : 'environment')
) {
videoSourceId = sourceInfo.deviceId;
}
}
mediaDevices
.getUserMedia({
audio: true,
video: {
mandatory: {
minWidth: 500, // Provide your own width, height and frame rate here
minHeight: 300,
minFrameRate: 30,
},
facingMode: isFront ? 'user' : 'environment',
optional: videoSourceId ? [{sourceId: videoSourceId}] : [],
},
})
.then(stream => {
// Got stream!
setLocalStream(stream);
// setup stream listening
yourConn.addStream(stream);
})
.catch(error => {
// Log error
});
});
yourConn.onaddstream = event => {
console.log('On Add Stream', event);
setRemoteStream(event.stream);
};
// Setup ice handling
yourConn.onicecandidate = event => {
if (event.candidate) {
send({
type: 'candidate',
candidate: event.candidate,
});
}
};
}, []);
const send = message => {
//attach the other peer username to our messages
if (connectedUser) {
message.name = connectedUser;
console.log('Connected iser in end----------', message);
}
conn.send(JSON.stringify(message));
};
const onCall = () => {
setCalling(true);
connectedUser = callToUsername;
console.log('Caling to', callToUsername);
// create an offer
yourConn.createOffer().then(offer => {
yourConn.setLocalDescription(offer).then(() => {
console.log('Sending Ofer');
console.log(offer);
send({
type: 'offer',
offer: offer,
});
// Send pc.localDescription to peer
});
});
};
//when somebody sends us an offer
const handleOffer = async (offer, name) => {
console.log(name + ' is calling you.');
console.log('Accepting Call===========>', offer);
connectedUser = name;
try {
await yourConn.setRemoteDescription(new RTCSessionDescription(offer));
const answer = await yourConn.createAnswer();
await yourConn.setLocalDescription(answer);
send({
type: 'answer',
answer: answer,
});
} catch (err) {
console.log('Offerr Error', err);
}
};
//when we got an answer from a remote user
const handleAnswer = answer => {
yourConn.setRemoteDescription(new RTCSessionDescription(answer));
};
//when we got an ice candidate from a remote user
const handleCandidate = candidate => {
setCalling(false);
console.log('Candidate ----------------->', candidate);
yourConn.addIceCandidate(new RTCIceCandidate(candidate));
};
//hang up
const hangUp = () => {
send({
type: 'leave',
});
handleLeave();
};
const handleLeave = () => {
connectedUser = null;
setRemoteStream({toURL: () => null});
yourConn.close();
// yourConn.onicecandidate = null;
// yourConn.onaddstream = null;
};
const onLogout = () => {
// hangUp();
AsyncStorage.removeItem('userId').then(res => {
navigation.push('Login');
});
};
const acceptCall = async () => {
console.log('Accepting Call===========>', offer);
connectedUser = offer.name;
try {
await yourConn.setRemoteDescription(new RTCSessionDescription(offer));
const answer = await yourConn.createAnswer();
await yourConn.setLocalDescription(answer);
send({
type: 'answer',
answer: answer,
});
} catch (err) {
console.log('Offerr Error', err);
}
};
const rejectCall = async () => {
send({
type: 'leave',
});
``;
setOffer(null);
handleLeave();
};
/**
* Calling Stuff Ends
*/
return (
<View style={styles.root}>
<View style={styles.inputField}>
<TextInput
label="Enter Friends Id"
mode="outlined"
style={{marginBottom: 7}}
onChangeText={text => setCallToUsername(text)}
/>
<Button
mode="contained"
onPress={onCall}
loading={calling}
// style={styles.btn}
contentStyle={styles.btnContent}
disabled={!(socketActive && userId.length > 0)}>
Call
</Button>
</View>
<View style={styles.videoContainer}>
<View style={[styles.videos, styles.localVideos]}>
<Text>Your Video</Text>
<RTCView streamURL={localStream.toURL()} style={styles.localVideo} />
</View>
<View style={[styles.videos, styles.remoteVideos]}>
<Text>Friends Video</Text>
<RTCView
streamURL={remoteStream.toURL()}
style={styles.remoteVideo}
/>
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
root: {
backgroundColor: '#fff',
flex: 1,
padding: 20,
},
inputField: {
marginBottom: 10,
flexDirection: 'column',
},
videoContainer: {
flex: 1,
minHeight: 450,
},
videos: {
width: '100%',
flex: 1,
position: 'relative',
overflow: 'hidden',
borderRadius: 6,
},
localVideos: {
height: 100,
marginBottom: 10,
},
remoteVideos: {
height: 400,
},
localVideo: {
backgroundColor: '#f2f2f2',
height: '100%',
width: '100%',
},
remoteVideo: {
backgroundColor: '#f2f2f2',
height: '100%',
width: '100%',
},
});
Why do i keep getting this error:
[Unhandled promise rejection: TypeError:null is not an object (evaluating '_InCallManager.checkCameraPermission')]
After Anik Dey Answer iget this stacktrace:
Error [TypeError: null is not an object (evaluating 'WebRTCModule.peerConnectionInit')]
TypeError: null is not an object (evaluating 'WebRTCModule.peerConnectionInit')
This error is located at:
in CallScreen (at SceneView.tsx:122)
in StaticContainer
in StaticContainer (at SceneView.tsx:115)
in EnsureSingleNavigator (at SceneView.tsx:114)
in SceneView (at useDescriptors.tsx:153)
in RCTView (at View.js:34)
in View (at CardContainer.tsx:245)
in RCTView (at View.js:34)
in View (at CardContainer.tsx:244)
in RCTView (at View.js:34)
in View (at CardSheet.tsx:33)
in ForwardRef(CardSheet) (at Card.tsx:573)
in RCTView (at View.js:34)
in View (at createAnimatedComponent.js:165)
in AnimatedComponent (at createAnimatedComponent.js:215)
in ForwardRef(AnimatedComponentWrapper) (at Card.tsx:555)
in PanGestureHandler (at GestureHandlerNative.tsx:13)
in PanGestureHandler (at Card.tsx:549)
in RCTView (at View.js:34)
in View (at createAnimatedComponent.js:165)
in AnimatedComponent (at createAnimatedComponent.js:215)
in ForwardRef(AnimatedComponentWrapper) (at Card.tsx:544)
in RCTView (at View.js:34)
in View (at Card.tsx:538)
in Card (at CardContainer.tsx:206)
in CardContainer (at CardStack.tsx:620)
in RCTView (at View.js:34)
in View (at Screens.tsx:84)
in MaybeScreen (at CardStack.tsx:613)
in RCTView (at View.js:34)
in View (at Screens.tsx:54)
in MaybeScreenContainer (at CardStack.tsx:495)
in CardStack (at StackView.tsx:462)
in KeyboardManager (at StackView.tsx:458)
in RNCSafeAreaProvider (at SafeAreaContext.tsx:76)
in SafeAreaProvider (at SafeAreaProviderCompat.tsx:42)
in SafeAreaProviderCompat (at StackView.tsx:455)
in GestureHandlerRootView (at GestureHandlerRootView.android.tsx:26)
in GestureHandlerRootView (at StackView.tsx:454)
in StackView (at createStackNavigator.tsx:87)
in StackNavigator (at App.js:15)
in EnsureSingleNavigator (at BaseNavigationContainer.tsx:409)
in ForwardRef(BaseNavigationContainer) (at NavigationContainer.tsx:91)
in ThemeProvider (at NavigationContainer.tsx:90)
in ForwardRef(NavigationContainer) (at App.js:14)
in App (created by ExpoRoot)
in ExpoRoot (at renderApplication.js:45)
in RCTView (at View.js:34)
in View (at AppContainer.js:106)
in RCTView (at View.js:34)
in View (at AppContainer.js:132)
in AppContainer (at renderApplication.js:39)
at node_modules\react-native\Libraries\LogBox\LogBox.js:148:8 in registerError
at node_modules\react-native\Libraries\LogBox\LogBox.js:59:8 in errorImpl
at node_modules\react-native\Libraries\LogBox\LogBox.js:33:4 in console.error
at node_modules\expo\build\environment\react-native-logs.fx.js:27:4 in error
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:104:6 in reportException
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:171:19 in handleException
at node_modules\react-native\Libraries\Core\ReactFiberErrorDialog.js:43:2 in showErrorDialog
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:15257:32 in logCapturedError
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:15361:20 in logError
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:16597:12 in update.callback
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:7106:2 in callCallback
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:7127:20 in commitUpdateQueue
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:15801:25 in commitLifeCycles
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:18744:22 in commitLayoutEffects
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:265:4 in invokeGuardedCallbackImpl
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:476:2 in invokeGuardedCallback
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:18483:29 in commitRootImpl
at [native code]:null in commitRootImpl
at node_modules\scheduler\cjs\scheduler.development.js:653:23 in unstable_runWithPriority
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:18317:17 in commitRoot
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:17697:12 in performSyncWorkOnRoot
at [native code]:null in performSyncWorkOnRoot
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5321:31 in runWithPriority$argument_1
at node_modules\scheduler\cjs\scheduler.development.js:653:23 in unstable_runWithPriority
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5316:21 in flushSyncCallbackQueueImpl
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:5304:28 in flushSyncCallbackQueue
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:17125:30 in scheduleUpdateOnFiber
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
change permissions to PERMISSIONS in permissionCheck function
for some reason my code wont run anymore and im unable to track down the error.
Error is presented in the debugger like this:
Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.
in LoginScreen (at SceneView.js:9)
in SceneView (at SwitchView.js:12)
in SwitchView (at createNavigator.js:61)
in Navigator (at createAppContainer.js:429)
in NavigationContainer (at App.js:19)
in App (at renderApplication.js:40)
in RCTView (at View.js:35)
in View (at AppContainer.js:98)
in RCTView (at View.js:35)
in View (at AppContainer.js:115)
in AppContainer (at renderApplication.js:39)
This error is located at:
in LoginScreen (at SceneView.js:9)
in SceneView (at SwitchView.js:12)
in SwitchView (at createNavigator.js:61)
in Navigator (at createAppContainer.js:429)
in NavigationContainer (at App.js:19)
in App (at renderApplication.js:40)
in RCTView (at View.js:35)
in View (at AppContainer.js:98)
in RCTView (at View.js:35)
in View (at AppContainer.js:115)
in AppContainer (at renderApplication.js:39)
As I understand it, its saying im trying to display an object. But i dont think that I am.
Here is my code, first app.js where the navigation is configured.
//imports are omitted
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
const CallLogStackNav = createStackNavigator({
Telefonlogg: {
screen: CallHistoryScreen,
navigationOptions: ({navigation}) => {
return {
headerTitle: 'Telefonlogg',
headerLeft: (
<Icon
style={{paddingLeft: 10}}
onPress={() => navigation.openDrawer()}
name="menu"
/>
),
};
},
},
Billing: {
screen: BillingScreen,
navigationOptions: ({navigation}) => {
return {
headerTitle: 'Time registrering',
};
},
},
});
const SettingsStackNav = createStackNavigator({
Instillinger: {
screen: SettingsScreen,
navigationOptions: ({navigation}) => {
return {
headerLeft: (
<Icon
style={{paddingLeft: 10}}
onPress={() => navigation.openDrawer()}
name="menu"
/>
),
headerTitle: 'Instillinger',
};
},
},
Svarteliste: {
screen: BlacklistScreen,
navigationOptions: ({navigation}) => {
return {
headerTitle: 'Svarteliste',
};
},
},
});
const AppDrawerNav = createDrawerNavigator({
Hjem: {screen: CallLogStackNav},
Instillinger: {screen: SettingsStackNav},
});
const AppSwitchNav = createSwitchNavigator({
Login: {screen: LoginScreen},
Dashboard: {screen: AppDrawerNav},
});
const AppContainer = createAppContainer(AppSwitchNav);
And heres the "LoginScreen" that i think is giving me the error (again imports are omitted):
class LoginScreen extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
username: '',
password: '',
};
}
async componentDidMount() {
const callHistory = await CallHistory.request.fetchCallHistory();
if (callHistory !== null) {
this.setState({callLogs: callHistory, isLoading: false});
await LocalStorage.function.setItem(
'#callLog.Origin',
this.state.callLogs,
);
}
}
async render() {
if (this.state.isLoading) {
return <SplashScreen />;
}
if ((await Auth.function.getToken()) !== 'err:noToken') {
this.props.navigation.navigate('Dashboard');
}
return (
<Container style={styles.wrapper}>
<ImageBackground
source={require('../assets/dlxbgxxxhdpi.png')}
style={styles.container}>
<View style={styles.formContainer}>
<TextInput
placeholder="Brukernavn"
style={styles.inputs}
onChangeText={text => this.setState({username: text})}
/>
<TextInput
placeholder="Passord"
style={styles.inputs}
onChangeText={text => this.setState({password: text})}
/>
<TouchableOpacity
style={styles.button}
onPress={async () => {
if (
(await Auth.function.login(
this.state.username,
this.state.password,
)) === true
) {
this.props.navigation.navigate('Dashboard');
} else {
this.setState({username: '', password: ''});
}
}}>
<Text style={styles.btText}> Logg Inn </Text>
</TouchableOpacity>
</View>
</ImageBackground>
</Container>
);
}
}
export default LoginScreen;
I have been trying to figure it out for some time now, and would appriciate it if someone could give me a hand.
lifecycle methods cant have the async modifiers.
remove async keywords from render() and componentDidMount()
My problem is the same with this one but I have difficulty what should I do if I'm using store provider like this:
const AppNavigator = createSwitchNavigator(
{
Loading: MainLoadingScreen,
App: MainNavigator,
Auth: AuthStack,
Signup: SignupStack
},
{
initialRouteName: 'Loading',
}
);
const App = () => {
return (
<Provider store={store}>
<View style={styles.container}>
<AppNavigator />
</View>
</Provider>
);
};
export default App;
I'm getting this error:
Invariant Violation: The navigation prop is missing for this navigator. In react-navigation 3 you must set up your app container directly. More info: https://reactnavigation.org/docs/en/app-containers.html
This error is located at:
in Navigator (at App.js:114)
in RCTView (at View.js:45)
in View (at App.js:113)
in Provider (at App.js:112)
in App (at withExpoRoot.js:20)
in RootErrorBoundary (at withExpoRoot.js:19)
in ExpoRootComponent (at renderApplication.js:35)
in RCTView (at View.js:45)
in View (at AppContainer.js:98)
in RCTView (at View.js:45)
in View (at AppContainer.js:115)
in AppContainer (at renderApplication.js:34)
- node_modules\#react-navigation\core\lib\module\navigators\createNavigator.js:1:1637 in getDerivedStateFromProps
- node_modules\react-native\Libraries\Renderer\oss\ReactNativeRenderer-dev.js:6896:46 in applyDerivedStateFromProps
- ... 20 more stack frames from framework internals
How do I convert my code so I can use the format shown here? :
const App = createAppContainer(AppNavigator)
Wrap your switch navigator with createAppContainer:
const MainSwitch = createSwitchNavigator(
{
Loading: MainLoadingScreen,
App: MainNavigator,
Auth: AuthStack,
Signup: SignupStack
},
{
initialRouteName: 'Loading',
}
);
const AppNavigator = createAppContainer(MainSwitch)
export default App = () => {
return (
<Provider store={store}>
<View style={styles.container}>
<AppNavigator />
</View>
</Provider>
);
};
Make it a function and assign it to the value of Const.
const App = function Appfunc() {
return (
<Provider store={store}>
<View style={styles.container}>
<AppNavigator />
</View>
</Provider>
);
}
const AppContainer = createAppContainer(AppNavigator)
export default AppContainer
I got this error message but I don't know!
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
Check the render method of `BackgroundDecorator`.
This error is located at:
in BackgroundDecorator (at BottomNavigation.js:130)
in RCTView (at View.js:71)
in View (at BottomNavigation.js:129)
in BottomNavigation (at App.js:80)
in RCTView (at View.js:71)
in View (at App.js:68)
in App (created by AwakeInDevApp)
in RCTView (at View.js:71)
in View (created by AwakeInDevApp)
in AwakeInDevApp (at registerRootComponent.js:35)
in RootErrorBoundary (at registerRootComponent.js:34)
in ExpoRootComponent (at renderApplication.js:35)
in RCTView (at View.js:71)
in View (at AppContainer.js:102)
in RCTView (at View.js:71)
in View (at AppContainer.js:122)
in AppContainer (at renderApplication.js:34)
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:5103:6 in createFiberFromElement
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:7379:8 in reconcileSingleElement
- ... 28 more stack frames from framework internals
my code is:
import React from 'react'
import { View, StyleSheet, Image } from 'react-native'
import BottomNavigation, {
IconTab,
Badge
} from 'react-native-material-bottom-navigation'
import Icon from '#expo/vector-icons/MaterialCommunityIcons'
export default class App extends React.Component {
state = {
activeTab: 'games'
}
tabs = [
{
key: 'games',
label: 'Games',
barColor: '#388E3C',
pressColor: 'rgba(255, 255, 255, 0.16)',
icon: 'gamepad-variant'
},
{
key: 'movies-tv',
label: 'Movies & TV',
barColor: '#00695C',
pressColor: 'rgba(255, 255, 255, 0.16)',
icon: 'movie'
},
{
key: 'music',
label: 'Music',
barColor: '#6A1B9A',
pressColor: 'rgba(255, 255, 255, 0.16)',
icon: 'music-note'
},
{
key: 'books',
label: 'Books',
barColor: '#1565C0',
pressColor: 'rgba(255, 255, 255, 0.16)',
icon: 'book'
}
]
state = {
activeTab: this.tabs[0].key
}
renderIcon = icon => ({ isActive }) => (
<Icon size={24} color="white" name={icon} />
)
renderTab = ({ tab, isActive }) => (
<IconTab
isActive={isActive}
showBadge={tab.key === 'movies-tv'}
renderBadge={() => <Badge>2</Badge>}
key={tab.key}
label={tab.label}
renderIcon={this.renderIcon(tab.icon)}
/>
)
render() {
return (
<View style={{ flex: 1, backgroundColor: 'white' }}>
<View style={{ flex: 1, justifyContent: 'flex-end' }}>
<Image
source={require('./cut.png')}
style={{
resizeMode: 'contain',
width: 412,
bottom: -120,
opacity: 0.5
}}
/>
</View>
<BottomNavigation
tabs={this.tabs}
activeTab={this.state.activeTab}
onTabPress={newTab => this.setState({ activeTab: newTab.key })}
renderTab={this.renderTab}
useLayoutAnimation
/>
</View>
)
}
}
in some cases change the way the component is created is enough
import React, { Component } from 'react'
export default class ComponentName extends Component {
}