The error message "TypeError: null is not an object (evaluating 'user.uid')" is commonly encountered in React Native when trying to access a

When I pulled the user.uid from the AuthContext using useContext, I encountered an error. Essentially, I want to allow the logged-in user to delete a shared post only if the userID matches the logged-in user's ID. However, when comparing user.uid == post.userId, I am getting this error: TypeError: null is not an object (evaluating 'user.uid'). How can I resolve this issue?

import { AuthContext } from "../../Pages/AuthProvider/AuthProvider";
const PostCard = ({post}) => {
    const {user} = useContext(AuthContext); 
    const userID=user.uid;
    return(
        <View style={styles.container}>
            <View style={styles.header}>
                <View style={styles.inner1_container}>
                    <Image
                        style={styles.profile_image}
                        source={ProfileImg}
                    />
                    <Text style={styles.username_text}>username</Text>
                </View>
                <View style={styles.inner2_container}>
                    <Text style={styles.like_text}>Likes: {post.likes}</Text>
                    <View style={styles.like_button}>
                    <TouchableWithoutFeedback
                        onPress={liked}
                    >
                        <Image
                            style={styles.like_button_image}
                            source={isLiked ? likedPaw : unLikedPaw}
                        />
                    </TouchableWithoutFeedback>
                    </View>
                </View>                
            </View>

            <View style={styles.describe_container}>
                <Text numberOfLines={8} style={styles.describe_text}>{post.description}</Text>
                {
                    post.contact != "" && (<>
                        <Text numberOfLines={2} style={styles.contact_text}>Contact: {iltetisimtext}{post.contact} </Text>
                    </>) 
                }
                <Text style={styles.time_text}>Share Time</Text>
                {
                    user.uid == post.userId && (<>
                    <Text style={styles.time_text}>Delete</Text>
                    </>)
                }
            </View>
        </View>        
    )
}

Answer №1

The issue arose from the user object being null at the time of logging out. I confirmed this by utilizing an if statement and successfully rectified the problem.

    function deletePostText(){
        if(user){
            if(user.uid == post.userId){
                 return(
                    <TouchableOpacity>
                        <Text style={styles.time_text}>Delete</Text>
                    </TouchableOpacity>
                )
            }
           }
        else{
            return;
        }
    }  

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble loading the script from the assets 'index.android.bundle'? Ensure that your bundle is properly packaged or that you have a packager server running

I encountered an issue while updating my React Native application from version 0.38.0 to 0.45.1. The error message I received is as follows: java.lang.RuntimeException: Unable to load script from assets 'index.android.bundle'. Make sure your bun ...

What could be the reason for my function failing to return true?

I have a function that can check if a script is loaded: function checkURLExistence(url){ $.ajax({ url: url, success: function(data){ //alert(url + ' exists'); console.log(url + ' exists'); return ...

What is the best method for removing extra spaces from an input field with type "text"?

I have an input field of type "text" and a button that displays the user's input. However, if there are extra spaces in the input, they will also be displayed. How can I remove these extra spaces from the input value? var nameInput = $('#name ...

When "this" doesn't refer to the current object, how to self reference an object

I am currently working on developing a modular series of element handlers for an application that features pages with different configurations. For example, the 'Hex T' configuration includes elements labeled from 'A' to 'O', ...

The button becomes inactive upon trying to insert a background

I'm currently working on customizing the Parse anypic tutorial UI and I am facing some challenges. Here is my ViewController: @interface PAPHomeViewController () @property (nonatomic, strong) PAPSettingsActionSheetDelegate *settingsActionSheetDelega ...

How can I access attribute type information in a Node.js Sequelize model?

I have successfully implemented a model in NodeJS using Postgres and sequelize. Let's say the model is Person and it includes fields for name and age. Now, I am looking to dynamically examine the model class to retrieve details about its attributes, s ...

Discover the power of positioning data labels in c3js!

Is there a way to adjust the position of labels above the data in a c3 bar chart? The official documentation explains how to modify the positions of labels on the x and y measurement axes by manipulating integers for y and x, but I couldn't find any i ...

Using React's useEffect to implement a mousedown event listener

I created a modal that automatically closes when the user clicks outside of it. method one - involves passing isModalOpened to update the state only if the modal is currently open. const [isModalOpened, toggleModal] = useState(false); const ref = useRef(n ...

Transferring PHP array data to JavaScript without being exposed in the source code

In the process of creating a historical database, I am currently handling over 2,000 photos that require categorization, out of which approximately 250 have already been uploaded. To efficiently store this data, I have set up a MySQL database with 26 field ...

Attempting to incorporate country flags into the Currency Converter feature

www.womenpalace.com hello :) i'm looking to customize my Currency Converter with Flags images. this is the code for the converter: <select id ="currencies" class="currencies" name="currencies" data-default-shop-currency="{{ shop.currency }}" ...

Deleting a row from the table with a single click on the X icon

Is there a way to delete individual rows in a table by clicking on a close icon instead of removing all rows at once? Additionally, I am looking for a better method to display rows in a table. You can view my current implementation here: link -> jsfiddl ...

Simple JavaScript Calculator

I'm currently working on a basic JavaScript Mortgage calculator, but I'm facing some challenges. I haven't implemented the math yet and I'm struggling to display the final sum (x + y + z) below the form after submission. The reset form ...

"Utilizing Vue.js to make an AJAX request and trigger another method within a

How can I include another method within a jQuery ajax call? methods : { calert(type,msg="",error=""){ console.log("call me"); }, getData(){ $.ajax({ type: "GET", success: function(data){ / ...

Associating checkbox options with an array that is void of elements

I have a series of arrays linked to checkboxes and I am trying to create a unique array based on the selected checkbox values. Here is an example of the HTML structure: <input type="checkbox" value="value1">Value 1 <input type="checkbox" value=" ...

Using AXIOS and VueJs to visually represent data with a two-dimensional array

I'm new to vuejs and I want to display my data response in a two-dimensional table. This is the data I have: [{ "origine": "", "nb": 15 }, { "origine": "?", "nb": 18 }, { "origine": "?L", "nb": 1 }, { "origine": "G", "nb": 298 }, { ...

Comparing two arrays in Javascript to find identical values

I am faced with a challenge involving three arrays. One array contains static values, another array contains dynamic values, and the third array is intended to store values that are present in both of the other arrays. My goal is to iterate through the ar ...

Issue communicating with connect-flash: flash variable is not recognized

I've been diving into books on node.js, express, and mongodb lately. In one of the examples, the author showcases the usage of connect-flash. However, I'm encountering some difficulties getting it to function as expected. Below are snippets from ...

What could be the reason for the malfunctioning of the "subscribe" button?

Whenever the subscribe button is clicked, it should send an email to the "subscriptions" section of the database. Unfortunately, when I click the button, nothing seems to happen. My understanding of this is very limited and I can't seem to troubleshoo ...

Sending an error from one asynchronous function to another

I have a complex system that utilizes async/await. My goal is to handle various types of errors from an async function within a single try/catch block. This function is called from another async function. Unfortunately, I've been unable to successfu ...

There was a failure in resolving all files necessary for the configuration ':app:debugRuntimeClasspath'

Encountering an error message: Execution failed for task ':app:desugarDebugFileDependencies'. Could not resolve all files for configuration ':app:debugRuntimeClasspath'. Could not find com.google.guava:listenablefuture:1.0. Additiona ...