Beep Boop
Beep Boop

Reputation: 337

React Native: Component Exception - Objects are not valid as a React child

I am using react-native-autocomplete-input to search and show list of addresses.

However upon searching I am getting 'Component Exception - Objects are not valid as a React child...' error.

When I console.log it shows the object results (list of addresses) but it fails to render it. Any help regarding this issue would be greatly appreciated.

I have provided my code snippet below along with the screenshot of the error.

Here's my code snippet:

 import 'react-native-gesture-handler';
import React from 'react';
import {
    SafeAreaView,
    StyleSheet,
    View,
    Text,
    FlatList,
    TouchableOpacity,
} from 'react-native';
import Config from '../config';
import Autocomplete from 'react-native-autocomplete-input';
import _debounce from 'lodash/debounce';

export default class AddAddressSearch extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            form: {
                address: '',
            },

            location: [],
            query: '',
        };

        this.onChangeLocationDebounce = _debounce(this.onChangeLocation, 200);
    }

    async onChangeLocation(input) {
        const COUNTRY_FORMAT = 'country:my';

        try {
            const result = await fetch(`https://maps.googleapis.com/maps/api/place/autocomplete/json?key=${Config.GOOGLE_API_KEY}&input=${input}&components=${COUNTRY_FORMAT}`);
            const data = await result.json();
            this.setState({ location: data.predictions });
        } catch (err) {
            // console.log("LocationPicker onChangeLocation err: ", err)
        }
    }

    searchLocation() {
        console.log('search result: ', this.state.location) //shows the results
        return (
            <View style={{ zIndex: 1 }}>
                <Autocomplete
                    autoCapitalize="none"
                    autoCorrect={false}
                    placeholder={'Search Location Name'}
                    data={this.state.location}
                    keyExtractor={(item) => item.place_id}
                    defaultValue={this.state.query}
                    onChangeText={(address) => {
                        console.log('typed: ', address)
                        this.onChangeLocationDebounce(address);
                    }}
                    renderItem={({ item }) => (
                        //you can change the view you want to show in suggestion from here
                        <TouchableOpacity
                            onPress={async () => {
                                this.setState({
                                    query: item.description,
                                    location: [],

                                    // form: {
                                    //   ...this.state.form,
                                    //   address: item.description,
                                    // }
                                });
                                try {
                                    const result = await fetch(`https://maps.googleapis.com/maps/api/place/details/json?placeid=${item.place_id}&key=${Config.GOOGLE_API_KEY}`,);
                                    const data = await result.json();

                                    let coordinate = data.result.geometry.location;
                                    let latitude = parseFloat(coordinate.lat).toFixed(8).toString();
                                    let longitude = parseFloat(coordinate.lng).toFixed(8).toString();

                                    this.setState({
                                        form: {
                                            ...this.state.form,
                                            latitude,
                                            longitude,
                                        },
                                    });
                                } catch (err) {
                                    // console.error(err);
                                }
                            }}>
                            <View
                                style={[
                                    styles.row,
                                    {
                                        marginHorizontal: 10,
                                        paddingVertical: 5,
                                        borderBottomWidth: 1,
                                        borderColor: '#e6e6e6',
                                    },
                                ]}>
                                <Text>{item.description}</Text>
                            </View>
                        </TouchableOpacity>
                    )}
                />
            </View>
        );
    }

    form() {
        return (
            <View style={{ margin: 20 }}>
                <View style={{ marginVertical: 5 }} />
                {this.searchLocation()}
            </View>
        );
    }


    renderView() {
        return (
            <SafeAreaView>
                {this.form()}
            </SafeAreaView>
        );
    }

    render() {
        return (
            <>
                <FlatList
                    ListHeaderComponent={this.renderView()}
                    ListHeaderComponentStyle={{ marginHorizontal: 20 }}
                    ListFooterComponentStyle={{ marginHorizontal: 20 }}
                />
            </>
        );
    }
};

I have used the same method on another project and it seems to work as intended on that project. Only on this new project I am facing this issue

Here's the screenshot of the error:

enter image description here

Upvotes: 1

Views: 101

Answers (1)

Ahmed Gaber
Ahmed Gaber

Reputation: 4004

this error shown because you use last version v5.2 or v5 with code working in v4.2 or min

you need to edit package.json with the version in other project or edit your code to last version
here the code for latest version, and see snack here.

//use flatListProps instead with renderItem, see this example
<Autocomplete
   data={data}
   value={query}
   onChangeText={(text) => this.setState({ query: text })}
   flatListProps={{
      keyExtractor: (_, idx) => idx,
      renderItem: ({ item }) => <Text>{item}</Text>,
   }}
/>

Upvotes: 1

Related Questions