Search code examples
javascriptfirebasereact-nativefirebase-realtime-databasesearchbar

React-native search bar - error: undefined is not a function (near '... this.state.books.filter...')


I can't figure out what I am doing wrong here.

I added a searchbar but when I write something in the textfield it gives me the error: "undefined is not a function (near '... this.state.books.filter...')"

Below is some of my code.

What am I doing wrong?

 state = {
    books: {},
};
componentDidMount() {
        firebase
        .database()
        .ref('/Books')
        .on('value', snapshot => {
            this.setState({ books: snapshot.val() });
        });
}
searchBooks = value => {
    const { books } = this.state;
    const bookArray = Object.values(books);
    const filteredBooks = bookArray.filter(book => {
        let bookLowercase = (book.bookname).toLowerCase();
        let searchTermLowercase = value.toLowerCase();
        return bookLowercase.indexOf(searchTermLowercase) > -1;
    });
    this.setState({ books: filteredBooks });
};

render() {
    const { books } = this.state;
    if (!books) {
        return null;
    }
    const bookArray = Object.values(books);
    const bookKeys = Object.keys(books);
    return (

        <View style={styles.container}>
            {/*Searchbar */}
            <View style={{ height: 80, backgroundColor: '#c45653', justifyContent: "center", paddingHorizontal: 5 }}>
                <View style={{ height: 50, backgroundColor: 'white', flexDirection: 'row', padding: 5, alignItems: 'center' }}>
                    <TextInput
                        style={{
                            fontSize: 24,
                            marginLeft: 15
                        }}
                        placeholder="Search"
                        onChangeText={value => this.searchBooks(value)}
                    />
                </View>
            </View>

            <FlatList
                style={{ backgroundColor: this.state.searchBarFocused ? 'rgba(0,0,0,0.3)' : 'white' }}
                data={bookArray}
                keyExtractor={(item, index) => bookKeys[index]}
                renderItem={({ item, index }) => (
                    <BookListItem
                        book={item}
                        id={bookKeys[index]}
                        onSelect={this.handleSelectBook}
                    />
                )}
            />
        </View>
    );

Solution

  • You're initializing this.state.books as an Object.

    state = {
        books: {},
    };
    

    Objects have no filter function. You probably want to use an Array instead.

    state = {
        books: [],
    };
    

    Then you'll be able to use this.state.books.filter() with the Array's filter function.