React native Algolia Search undefined is not an object - javascript

import React, { Component } from "react";
import PropTypes from "prop-types";
import { View, StyleSheet, TextInput } from "react-native";
import algoliasearch from "algoliasearch/lite";
import { InstantSearch } from "react-instantsearch-native";
import {
connectSearchBox,
connectInfiniteHits,
connectHits,
connectAutoComplete,
connectStateResults,
} from "react-instantsearch/connectors";
import { FlatList } from "react-native-gesture-handler";
class SearchBox extends Component {
render() {
return (
<View style={styles.searchBoxContainer}>
<TextInput
style={styles.searchBox}
onChangeText={(query) => {
this.props.refine(query);
}}
placeholder={"Search Gangs"}
clearButtonMode={"always"}
clearButtonMode={"always"}
spellCheck={false}
autoCorrect={false}
autoCapitalize={"none"}
/>
</View>
);
}
}
const ConnectedSearchBox = connectSearchBox(SearchBox);
class InfiniteHits extends Component {
onEndReached = () => {
if (this.props.hasMore) {
this.props.refine();
}
};
render() {
return (
<FlatList
renderItem={({ item }) => (
<View>
<Text>{item.basicData.selectedStudentName}</Text>
</View>
)}
data={this.props.hits}
keyExtractor={(item) => item.objectID}
onEndReached={this.onEndReached}
ItemSeparatorComponent={() => <View style={styles.ItemSeparator} />}
/>
);
}
}
const ConnectedInfiniteHits = connectInfiniteHits(InfiniteHits);
class SearchGangsAlgolia extends Component {
constructor(props) {
super(props);
}
render() {
console.log(this.props);
return (
<View
style={{
flex: 1,
alignItems: "center",
flexDirection: "column",
paddingTop: 20,
}}
>
<InstantSearch
appId=""
apiKey=""
indexName="criminals"
>
<ConnectedSearchBox />
<ConnectedInfiniteHits />
</InstantSearch>
</View>
);
}
}
const styles = StyleSheet.create({});
export default SearchGangsAlgolia;
Here in the above code, I'm trying to fetch data from algolia, as search results but, I'm getting error
in the page as "Type error, undefined is not an object(Evaluating 'client.addAlgoliaAgent') this error is located at InstantSearch. I don't know whether which npm package to install or to import from any of npm package. But it's throwing error in instantsearch".

If anybody is still looking for the answer, the reason why you're getting this error is because you did not include the property searchClient in your InstantSearch component
install algoliasearch (npm install algoliasearch ) and import it and use it like this:
import algoliasearch from "algoliasearch/lite";
create the searchClient as follows
const searchClient = algoliasearch("appId", "apiKey");
then finally include it in your InstantSearch component like this:
<InstantSearch
appId=""
apiKey=""
indexName="criminals"
searchClient={searchClient}
>
<ConnectedSearchBox />
<ConnectedInfiniteHits />
</InstantSearch>
It worked for me

Related

React native View' cannot be used as a JSX component. Its instance type 'View' is not a valid JSX element

I´am currently getting the following error on the View component inside App.tsx: 'View' cannot be used as a JSX component. Its instance type 'View' is not a valid JSX element
I think the issue is related to the library
import React from 'react';
import {View,Text,StyleSheet, Button} from 'react-native'
import {createSwitchNavigator} from 'react-navigation'
const styles = StyleSheet.create({
txt:{
fontSize: 48
},
view: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
})
class screenComponent1 extends React.Component {
render() {
return(
<View>
<Button onPress={() => this.props.navigation.navigate('screenroute2')} title='next page'/>
</View>
)
}
}
class screenComponent2 extends React.Component {
render() {
return(
<View>
<Button onPress={() => this.props.navigation.navigate('screenroute1')} title='next page'/>
</View>
)
}
}
const AppNavigator = createSwitchNavigator({
screenroute1: screenComponent1,
screenroute2: screenComponent2,
})
export default class App extends React.Component {
render() {
return <AppNavigator/>
}
}

pass multiple methods from parent to child component in react

I have created Table component. In this component i have created two buttons. one for download and second is share. both have onPress method. I have imported this Table component in the dashboard component. but I am unable to use both methods individually in my dashboard component.please suggest any solution for this problem.
Table Component:
import React, { StrictMode, useEffect, useState } from "react";
import { Text, View, ActivityIndicator } from "react-native";
import Size from "../../constants/Sizes";
import Strings from "../../constants/Strings";
import { Table, TableWrapper, Row, Rows } from "react-native-table-component";
import Color from "../../constants/Colors";
import Icon from "../../styles/Icons";
import api from "../../services/api";
import ListModel from "../ListModal";
import { TableTwoStyle as tableStyle } from "../../styles";
import { heightToDp } from "../../constants/Utils";
const TableTwo = (props) => {
const [files, setFiles] = useState([]);
const [modalState, setModalState] = useState(false);
useEffect(() => {
const fileData = api.getFileOptions();
setFiles(fileData);
}, []);
const { data } = props;
const handleOptions = (title) => {
console.log("title", title);
props.onPress(title);
// this.closeModal();
};
const openModal = () => {
setModalState(true);
};
const closeModal = () => {
setModalState(false);
};
return (
<StrictMode>
{data !== undefined ? (
<View style={tableStyle.mainContainer}>
<View style={tableStyle.HeadingSection}>
<View style={tableStyle.LabelContainer}>
<View style={tableStyle.leftSection}>
<Text style={tableStyle.labelText}>{Strings.tableTitle}</Text>
</View>
<View style={tableStyle.rightSection}>
<Icon.MaterialIcons
name="file-download"
color={Color.gray}
style={tableStyle.exportButton}
size={heightToDp(Size.per_4_5)}
onPress={openModal}
/>
</View>
<View style={tableStyle.rightSection}>
<Icon.MaterialIcons
name="share"
color={Color.info}
style={tableStyle.exportButton}
size={heightToDp(Size.per_4)}
onPress={openModal}
/>
</View>
</View>
<View style={tableStyle.divider} />
</View>
<View style={tableStyle.TableSection}>
{data.headers && data.headers.length > 0 ? (
<Table
borderStyle={{
borderWidth: Size.px_1,
borderColor: Color.dividerColor,
}}
>
<Row
data={data.headers}
flexArr={[Size.num_1]}
style={tableStyle.head}
textStyle={tableStyle.headerText}
/>
<TableWrapper style={tableStyle.wrapper}>
<Rows
data={data.data}
flexArr={[Size.num_1]}
style={tableStyle.row}
textStyle={tableStyle.text}
/>
</TableWrapper>
</Table>
) : (
<ActivityIndicator color={Color.loaderColor} size={Strings.lg} />
)}
</View>
<ListModel
modalState={modalState}
close={closeModal}
onPress={handleOptions}
data={files}
/>
</View>
) : null}
</StrictMode>
);
};
export default TableTwo;
Dashboard Component:
import React, { StrictMode, Component } from "react";
import { View, ScrollView } from "react-native";
import { GraphCardList as GraphList } from "../components";
import { InfoCardList as InfoList } from "../components";
import { TableTwo as Table } from "../components";
import Loader from "../components/Loader";
import Store from "../database/Storage";
import OptionsCard from "../components/Option";
import { Card as CardUI } from "../components";
import { dashboardStyle as dashboardUI } from "../styles";
import Api from "../services/api";
import inputValidation from "../helper/Validation";
import TableExport from "../exports/TableExport";
import Permission from "../services/AppPermission";
export default class DashboardScreen extends Component {
constructor(props) {
super(props);
this.state = {
tableList: [],
};
this.downloadData = this.downloadData.bind(this);
}
componentDidMount() {
}
componentWillUnmount() {
}
downloadData(title) {
...
}
shareData(){
....
}
render() {
const {
loader2,
infoList,
chartList,
tableList,
userList,
loader,
pauseState,
} = this.state;
//console.log("users",infoList);
if (loader) {
return (
<View style={dashboardUI.mainContainer}>
<Loader />
</View>
);
}
return (
<StrictMode>
<CardUI style={dashboardUI.Cards}>
<Table data={tableList} onPress={this.downloadData} />
</CardUI>
)}
</StrictMode>
);
}
}
If your'e passing same prop for two different buttons that means that the two buttons will execute the same method , but if you want to pass different methods for each button just pass a different props.
For example component B:
<View>
<Button title="Download" onPress={props.download}/>
<Button title="Share" onPress={props.share}/>
</View>
Component A:
<B download={this.downloadData} share={this.shareData}/>
Please try below code:
**In Dashboard Component:**
downloadData() {
}
`return (<Table data={tableList} handleDownloadData={this.downloadData} />);`
**In Table Component:**
const download = (data) => {
props.handleDownloadData(data);
};
const share = (data) => {
props.handleDownloadData(data);
};`
`return (<div><Button onClick={download}> Download</Button><Button onClick={share}> Share</Button></div>);
`

Navigate Between Screen React Native

I'm coming from ReactJS and a bit confused about how to navigate between screens in react native.
I'm using these react-navigation and react-navigation-stack versions:
"#react-navigation/native": "^5.8.10", "#react-navigation/stack": "^5.12.8"
So I have 2 screens already:
SplashScreenContainer
import React from 'react';
import {Text, View} from "react-native-reanimated";
class SplashScreenContainer extends React.PureComponent {
redirectToHome = () => {
const {navigation} = this.props;
navigation.navigate('HomeContainer');
}
render() {
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text onPress={() => this.redirectToHome}>
Splash Screen
</Text>
</View>
)
}
}
export default SplashScreenContainer;
HomeScreenContainer
import React from 'react';
import {Text, View} from "react-native-reanimated";
class HomeScreenContainer extends React.PureComponent {
render() {
return (
<View>
<Text>Home Screen</Text>
</View>
)
}
}
export default HomeScreenContainer;
and here's my app js to render the screens inside NavigationContainer:
App.js
import React from 'react';
import {SafeAreaView} from "react-native-safe-area-context";
import {NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
const SplashScreenContainer = React.lazy(() => import('./app/containers/SplashScreenContainer'));
const HomeContainer = React.lazy(() => import('./app/containers/HomeContainer'));
const Stack = createStackNavigator();
class App extends React.PureComponent {
render() {
return (
<SafeAreaView>
<NavigationContainer>
<Stack.Navigatior>
<Stack.Screen name='SplashScreenContainer' component={() => <SplashScreenContainer {...this.props} />}/>
<Stack.Screen name='HomeContainer' component={() => <HomeContainer {...this.props} />}/>
</Stack.Navigatior>
</NavigationContainer>
</SafeAreaView>
)
}
}
export default App;
After I run with npm run ios command, the console gives me this error:
Error: 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.
I don't understand what is this error about, what am I missing here? how can I navigate between the screens in react-native?
Any help will be much appreciated.
Thank You.
Regards
Well, I made it works. Here are the changes I made:
Remove SafeAreaView from App.js
Add {Suspense} in App.js because I forgot that React.lazy depends on Suspense
Use SafeAreaView in Home and SplashScreen imported from 'react-native'
App.js
import React, {Suspense} from 'react';
import {SafeAreaView, Text} from 'react-native';
import {NavigationContainer} from '#react-navigation/native';
import {createStackNavigator} from '#react-navigation/stack';
const SplashScreenContainer = React.lazy(() => import('./app/containers/SplashScreenContainer'));
const HomeContainer = React.lazy(() => import('./app/containers/HomeContainer'));
const Stack = createStackNavigator();
const Loading = () => {
return (
<SafeAreaView>
<Text>Loading</Text>
</SafeAreaView>
)
};
const Routes = () => {
return (
<NavigationContainer>
<Stack.Navigator initialRouteName='SplashScreenContainer'>
<Stack.Screen
name='SplashScreenContainer'
component={SplashScreenContainer}
options={{ headerShown: false }}
/>
<Stack.Screen
name='HomeContainer'
component={HomeContainer}
options={{ headerShown: false }}
/>
</Stack.Navigator>
</NavigationContainer>
)
}
class App extends React.PureComponent {
render() {
return (
<Suspense fallback={<Loading/>}>
<Routes/>
</Suspense>
)
}
}
export default App;
SplashScreenContainer.js
import React from 'react';
import {Button, SafeAreaView} from 'react-native';
class SplashScreenContainer extends React.PureComponent {
constructor(props) {
super(props);
}
redirectToHome = () => {
const {navigation} = this.props;
navigation.navigate('HomeContainer');
};
render() {
return (
<SafeAreaView style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Button onPress={() => this.redirectToHome()} title='Go To Home Screen'/>
</SafeAreaView>
)
}
}
export default SplashScreenContainer;
HomeScreenContainer.js
import React from 'react';
import {Button, SafeAreaView} from 'react-native';
class HomeContainer extends React.PureComponent {
redirectToSplash = () => {
const {navigation} = this.props;
navigation.navigate('SplashScreenContainer');
};
render() {
return (
<SafeAreaView style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Button onPress={() => this.redirectToSplash()} title='Go To Splash Screen'/>
</SafeAreaView>
)
}
}
export default HomeContainer;
Everything's working now, I'm able to switch between SplashScreen and HomeScreen when button is clicked/tapped.

ERROR: Touchable child must either be native or forward setNativeProps to a native component

I am currently doing ReactNative course from coursera and the course is 4 years old and i am facing this error: Touchable child must either be native or forward setNativeProps to a native component.
I've no idea what this is. It will be greatly helpful if someone will help me.Adding files details as well:
App.js
import React from 'react';
import Main from './components/MainComponent';
export default class App extends React.Component {
render() {
return (
<Main />
);
}
}
MainComponent.js
import React, { Component } from 'react';
import Menu from './MenuComponent';
import { DISHES } from '../shared/dishes';
import Dishdetail from './DishdetailComponent';
import { View } from 'react-native';
class Main extends Component {
constructor(props) {
super(props);
this.state = {
dishes: DISHES,
selectedDish: null,
};
}
onDishSelect(dishId) {
this.setState({selectedDish: dishId})
}
render() {
return (
<View style={{flex:1}}>
<Menu dishes={this.state.dishes} onPress={(dishId) => this.onDishSelect(dishId)} />
<Dishdetail dish={this.state.dishes.filter((dish) => dish.id === this.state.selectedDish)[0]} />
</View>
);
}
}
export default Main;
MenuComponent.js
import React from 'react';
import { View, FlatList } from 'react-native';
import { ListItem } from 'react-native-elements';
function Menu(props) {
const renderMenuItem = ({item, index}) => {
return (
<View>
<ListItem
key={index}
title={item.name}
subtitle={item.description}
hideChevron={true}
onPress={() => props.onPress(item.id)}
leftAvatar={{ source: require('./images/uthappizza.png')}}
/>
</View>
);
};
return (
<View>
<FlatList
data={props.dishes}
renderItem={renderMenuItem}
keyExtractor={item => item.id.toString()}
/>
</View>
);
}
export default Menu;
Dishdetailcomponent.js
import React from 'react';
import { Text, View } from 'react-native';
import { Card } from 'react-native-elements';
function Dishdetail(props) {
return(
<View >
<RenderDish dish={props.dish} />
</View>
);
}
function RenderDish(props) {
const dish = props.dish;
if (dish != null) {
return(
<View>
<Card
featuredTitle={dish.name}
image={require('./images/uthappizza.png')}>
<Text style={{margin: 10}}>
{dish.description}
</Text>
</Card>
</View>
);
}
else {
return(<View></View>);
}
}
export default Dishdetail;
Help will be appreciated!!
Thanks
I had same issue some days before. Quickfix for this issue.
import TouchableOpacity form 'react-native';
Add following in the MenuComponent.js
<ListItem
Component={TouchableOpacity}
key={item.id}
title={item.name}
subtitle={item.description}
hideChevron={true}
onPress={() => props.onPress(item.id)}
leftAvatar={{ source: require('./images/uthappizza.png')}}
/>
and run the program again. This will fix your problem.

Invariant Violation: Invariant Violation: Tried to get frame for out of range index NaN while rendering List

I was trying to develop a React Native app that has a Taxi search page with two search boxes, 'Pick Up' and 'Drop off'. I have used the google-places api for them and displayed the search results. My pick-up search box works perfectly fine. The same code when i use for my drop-off with few changes indicating 'Drop-off' throws error. I am unable to figure out what is going wrong. I face the following error:
Invariant Violation: Invariant Violation: Tried to get frame for out of range index NaN
in VirtualizedList (at FlatList.js:634) in FlatList (at List.js:12) in List (at connectStyle.js:392) in Styled(List) (at SearchResults/index.js:13) in RCTView (at View.js:35) in View (at View.js:10)
My Search Box code is the following:
import React from "react";
import {Text, PermissionsAndroid} from "react-native";
import styles from "./SearchBoxStyles";
import {View, InputGroup, Input} from "native-base";
import Icon from "react-native-vector-icons/FontAwesome";
export const SearchBox = ({getInputData, toggleSearchResultModal,getAddressPredictions}) =>{
function handleInput(key, val){
getInputData({
key,
value: val
});
getAddressPredictions();
}
return(
<View style={styles.searchBox}>
<View style={styles.inputWrapper}>
<Text style ={styles.label}>PICK UP</Text>
<InputGroup>
<Icon name="search" size={15} color="#FF5E3A"/>
<Input onFocus={()=>toggleSearchResultModal("pickUp")} style = {styles.inputSearch} placeholder="Choose pick up location" onChangeText={handleInput.bind(this,"pickUp")}/>
</InputGroup>
</View>
<View style={styles.inputWrapper}>
<Text style ={styles.label}>DROP OFF</Text>
<InputGroup>
<Icon name="search" size={15} color="#FF5E3A"/>
<Input onFocus={()=>toggleSearchResultModal("dropOff")} style = {styles.inputSearch} placeholder="Choose drop off location" onChangeText={handleInput.bind(this,"dropOff")}/>
</InputGroup>
</View>
</View>
);
}
export default SearchBox;
My Search results code is as the following:
import React from "react";
import {Text, PermissionsAndroid} from "react-native";
import styles from "./SearchResultsStyles";
import {View, List, ListItem, Left, Item, Body} from "native-base";
import Icon from "react-native-vector-icons/MaterialIcons";
export const SearchResults = ({predictions, getSelectedAddress}) =>{
function handleSelectedAddress(placeID){
getSelectedAddress(placeID)
}
return(
<View style={styles.searchResultsWrapper}>
<List
dataArray = {predictions}
renderRow ={(item)=>
<View>
<ListItem onPress={()=>handleSelectedAddress(item.placeID)} button avatar>
<Left style={styles.leftContainer}>
<Icon style={styles.leftIcon} name="location-on"/>
</Left>
<Body>
<Text style={styles.primaryText}>{item.primaryText}</Text>
<Text style={styles.secondaryText}>{item.secondaryText}</Text>
</Body>
</ListItem>
</View>
}
/>
</View>
);
}
export default SearchResults;
This is being rendered in:
import React from "react";
import {View} from "native-base";
import MapView from "react-native-maps";
import styles from "./MapContainerStyles"
import SearchBox from "../SearchBox";
import SearchResults from "../SearchResults";
const MapContainer = ({region, getInputData, toggleSearchResultModal, getAddressPredictions, resultTypes, predictions, getSelectedAddress}) =>{
return(
<View style={styles.container}>
<MapView
provider={MapView.PROVIDER_GOOGLE}
style={styles.map}
region={region}
>
<MapView.Marker
coordinate={region}
pinColor="green"
/>
</MapView>
<SearchBox
getInputData={getInputData}
toggleSearchResultModal={toggleSearchResultModal}
getAddressPredictions={getAddressPredictions}
/>
{ (resultTypes.pickUp || resultTypes.dropOff) &&
<SearchResults predictions={predictions} getSelectedAddress={getSelectedAddress}/>
}
</View>
)
}
export default MapContainer;
The following is the code related to my actions:
export function getInputData(payload){
return{
type:GET_INPUT,
payload
}
}
//toggle search result model
export function toggleSearchResultModal(payload){
return{
type:TOGGLE_SEARCH_RESULT,
payload
}
}
// GET ADDRESSES FROM GOOGLE PLACES
export function getAddressPredictions(){
return(dispatch, store)=>{
let userInput = store().home.resultTypes.pickUp ? store().home.inputData.pickUp : store().home.inputData.dropOff;
RNGooglePlaces.getAutocompletePredictions(userInput,
{
country:"us"
}
)
.then((results)=>
dispatch({
type:GET_ADDRESS_PREDICTIONS,
payload:results
})
)
.catch((error)=>console.log(error.message));
};
}
The following are the corresponding handlers:
function handleGetInputData(state, action){
const {key, value} =action.payload;
return update(state,{
inputData:{
[key]:{
$set:value
}
}
});
}
function handleToggleSearchResult(state, action){
if(action.payload === "pickUp"){
return update(state, {
resultTypes:{
pickUp:{
$set : true,
},
dropOff:{
$set : false
},
predictions:{
$set :{}
}
}
})
}
if(action.payload === "dropOff"){
return update(state, {
resultTypes:{
pickUp:{
$set : false,
},
dropOff:{
$set : true
}
},
predictions:{
$set :{}
}
})
}
}
function handleGetAddressPredictions(state,action){
return update(state,{
predictions:{
$set:action.payload
}
})
}
function handleGetSelectedAddress(state,action){
let selectedTitle = state.resultTypes.pickUp ? "selectedPickUp" : "selectedDropOff"
return update(state,{
selectedAddress:{
[selectedTitle]:{
$set:action.payload
}
},
resultTypes:{
pickUp: {
$set : false
},
dropOff:{
$set : false
}
}
})
}
I cant figure out the problem. Could someone help. Thanks in advance!!!
This is because of List is depreciated in react-native version 0.6. So you can use react-native components without using native base as follows.
import React from "react";
import { Text,ScrollView ,FlatList,View} from "react-native";
import Icon from "react-native-vector-icons/MaterialIcons";
import styles from "./searchResultsStyles";
export const SearchResults = ({ predictions, getSelectedAddress }) => {
function handleSelectedAddress(placeID) {
getSelectedAddress(placeID)
}
return (
< ScrollView style={styles.searchResultsWrapper} >
<FlatList
data={predictions}
renderItem={({ item }) => {
return <View style={styles.row}>
<View style={styles.leftContainer}>
<Icon style={styles.leftIcon} name="location-on" />
</View>
<Text style={styles.primaryText}>{item.primaryText}</Text>
<Text style={styles.secondaryText}>{item.secondaryText}</Text>
</View>
}}
/>
</ScrollView >
);
};
export default SearchResults;

Categories