Home > Net >  TypeError: undefined is not an object (evaluating '_this.renderPost')
TypeError: undefined is not an object (evaluating '_this.renderPost')

Time:03-19

I am trying to develop a React Native application. I have made a feed to render posts from the Firestore database. The weird thing is when I run the app for the first time it loads everything without an issue. However, after I add a post to the database I go and refresh the feed page to see the added post then I get this error. I would be thankful if anyone can tell me why.

Log of the error I get:

TypeError: undefined is not an object (evaluating '_this.renderPost')

This error is located at:
    in CellRenderer (created by VirtualizedList)
    in RCTView (created by View)
    in View (created by ScrollView)
    in RCTScrollView (created by ScrollView)
    in ScrollView (created by ScrollView)
    in ScrollView (created by VirtualizedList)
    in VirtualizedListContextProvider (created by VirtualizedList)
    in VirtualizedList (created by FlatList)
    in FlatList (created by Feed)
    in RCTView (created by View)
    in View (created by Feed)
    in Feed (created by SceneView)
    in StaticContainer
    in EnsureSingleNavigator (created by SceneView)
    in SceneView (created by BottomTabView)
    in RCTView (created by View)
    in View (created by Screen)
    in RCTView (created by View)
    in View (created by Background)
    in Background (created by Screen)
    in Screen (created by BottomTabView)
    in RNSScreen (created by AnimatedComponent)
    in AnimatedComponent
    in AnimatedComponentWrapper (created by Screen)
    in MaybeFreeze (created by Screen)
    in Screen (created by MaybeScreen)
    in MaybeScreen (created by BottomTabView)
    in RNSScreenContainer (created by ScreenContainer)
    in ScreenContainer (created by MaybeScreenContainer)
    in MaybeScreenContainer (created by BottomTabView)
    in RCTView (created by View)
    in View (created by SafeAreaInsetsContext)
    in SafeAreaProviderCompat (created by BottomTabView)
    in BottomTabView (created by BottomTabNavigator)
    in Unknown (created by BottomTabNavigator)
    in BottomTabNavigator (created by Main)
    in Main (created by SceneView)
    in StaticContainer
    in EnsureSingleNavigator (created by SceneView)
    in SceneView (created by CardContainer)
    in RCTView (created by View)
    in View (created by CardContainer)
    in RCTView (created by View)
    in View (created by CardContainer)
    in RCTView (created by View)
    in View
    in CardSheet (created by Card)
    in RCTView (created by View)
    in View (created by AnimatedComponent)
    in AnimatedComponent
    in AnimatedComponentWrapper (created by PanGestureHandler)
    in PanGestureHandler (created by PanGestureHandler)
    in PanGestureHandler (created by Card)
    in RCTView (created by View)
    in View (created by AnimatedComponent)
    in AnimatedComponent
    in AnimatedComponentWrapper (created by Card)
    in RCTView (created by View)
    in View (created by Card)
    in Card (created by CardContainer)
    in CardContainer (created by CardStack)
    in RNSScreen (created by AnimatedComponent)
    in AnimatedComponent
    in AnimatedComponentWrapper (created by Screen)
    in MaybeFreeze (created by Screen)
    in Screen (created by MaybeScreen)
    in MaybeScreen (created by CardStack)
    in RNSScreenContainer (created by ScreenContainer)
    in ScreenContainer (created by MaybeScreenContainer)
    in MaybeScreenContainer (created by CardStack)
    in RCTView (created by View)
    in View (created by Background)
    in Background (created by CardStack)
    in CardStack (created by HeaderShownContext)
    in RNCSafeAreaProvider (created by SafeAreaProvider)
    in SafeAreaProvider (created by SafeAreaInsetsContext)
    in SafeAreaProviderCompat (created by StackView)
    in GestureHandlerRootView
    in GestureHandlerRootView (created by StackView)
    in StackView (created by StackNavigator)
    in Unknown (created by StackNavigator)
    in StackNavigator (created by App)
    in EnsureSingleNavigator
    in BaseNavigationContainer
    in ThemeProvider
    in NavigationContainerInner (created by App)
    in App (created by ExpoRoot)
    in ExpoRoot
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
import { React, useState, useEffect } from "react";
import {
    View,
    Text,
    StyleSheet,
    Image,
    FlatList,
    TouchableOpacity,
} from "react-native";
import { Ionicons, MaterialIcons } from "@expo/vector-icons";
import { useNavigation } from "@react-navigation/core";
import { auth, storage, firestore } from "../firebase";
import { preventAutoHideAsync } from "expo-splash-screen";

function Feed() {
    const [posts, setPosts] = useState("");
    const [loading, setLoading] = useState(true);
    //const [deleted, setDeleted] = useState(false);

    const fetchPosts = async () => {
    try {
        const list = [];

        await firestore
        .collection("posts")
        .get()
        .then((querySnapshot) => {
            console.log("Total Posts: ", querySnapshot.size);

            querySnapshot.forEach((doc) => {
            const { userId, postImg, post, likes, comments } = doc.data();
            list.push({
                id: doc.id,
                userId,
                userName: auth.currentUser.email,
                userImg: require("../assets/couch.jpg"),
                post,
                postImg,
                liked: false,
                likes,
                comments,
            });
            });
        });

        setPosts(list);

        if (loading) {
        setLoading(false);
        }

        console.log("Posts: ", posts);
    } catch (e) {
        console.log(e);
    }
    };

    useEffect(() => {
    fetchPosts();
    }, []);

    //console.log(posts.userName)

    renderPost = (posts) => {
    return (
        <View style={styles.feedItem}>
        <Image source={posts.userImg} style={styles.avatar} />
        <View style={{ flex: 1 }}>
            <View
            style={{
                flexDirection: "row",
                justifyContent: "space-between",
                alignItems: "center",
            }}
            >
            <View>
                <Text style={styles.name}>{posts.userName}</Text>
            </View>

            <MaterialIcons name="expand-more" size={24} color="#73788B" />
            </View>
            <Text style={styles.post}>{posts.post}</Text>
            <Image
            source={{uri: posts.postImg}}
            style={styles.postImage}
            resizeMode="cover"
            />
            <View style={{ flexDirection: "row" }}>
            <Ionicons
                name="heart-outline"
                size={24}
                color="#73788B"
                style={{ marginRight: 16 }}
            />
            <Ionicons name="chatbox-outline" size={24} color="#73788B" />
            </View>
        </View>
        </View>
    );
    };
    return (
    <View style={styles.container}>
        <View style={styles.header}>
        <Text style={styles.headerTitle}>Feed</Text>
        <TouchableOpacity style={styles.addButton}>
            <Ionicons name="add-circle" size={32} color="black" />
        </TouchableOpacity>
        </View>

        <FlatList
        style={styles.feed}
        data={posts}
        renderItem={({ item }) => this.renderPost(item)}
        keyExtractor={(item) => item.id}
        showsVerticalScrollIndicator={false}
        ></FlatList>
    </View>
    );
}

const styles = StyleSheet.create({
    addButton: {
    position: "absolute",
    right: 30,
    top: 60,
    },
    container: {
    flex: 1,
    backgroundColor: "#EBECF4",
    },
    header: {
    paddingTop: 64,
    paddingBottom: 16,
    backgroundColor: "#FFF",
    alignItems: "center",
    justifyContent: "center",
    borderBottomWidth: 1,
    borderBottomColor: "#EBECF4",
    shadowColor: "#454D65",
    shadowOffset: { height: 5 },
    shadowRadius: 15,
    shadowOpacity: 0.2,
    zIndex: 10,
    },
    headerTitle: {
    fontSize: 20,
    fontWeight: "500",
    },
    feed: {
    marginHorizontal: 16,
    },
    feedItem: {
    backgroundColor: "#FFF",
    borderRadius: 5,
    padding: 8,
    flexDirection: "row",
    marginVertical: 8,
    },
    avatar: {
    width: 36,
    height: 36,
    borderRadius: 18,
    marginRight: 16,
    },
    name: {
    fontSize: 15,
    fontWeight: "500",
    color: "#454D65",
    },
    timestamp: {
    fontSize: 11,
    color: "#C4C6CE",
    marginTop: 4,
    },
    post: {
    marginTop: 16,
    fontSize: 14,
    color: "#838899",
    },
    postImage: {
    width: 267,
    height: 150,
    borderRadius: 5,
    marginVertical: 16,
    },
});
export default Feed;

Screeen shot of the error I get

CodePudding user response:

In a function component, you shouldn't be using this at all -- that's for use inside class components.

And, you should be declaring renderPost as a variable. So, change your code to:

const renderPost = (posts) => {

And remove this. in:

renderItem={({ item }) => this.renderPost(item)}
  • Related