skip to Main Content

profile/view.js

const ViewProfile = () => {
    const router = useRouter();

    //Working as expected
    const user = useUserData();
    console.log(user);

    //unable to fetch this
    const data = user.profile;
    console.log(data);

    //Rest of the code
}

This is my ViewProfile component. Whenever I fetch user data through useUserData hook, I can log the user object without any issue. But as soon as I try to access the user.profile object, I get an error Cannot read properties of null (reading 'profile').

useUserData.js

import Cookies from "js-cookie";
import { useEffect, useState } from "react";

const useUserData = () => {
    const userToken = Cookies.get("sessionToken");
    const [userData, setUserData] = useState(null);

    useEffect(() => {
        async function fetchData() {
            try {
                const res = await fetch(`${process.env.NEXT_PUBLIC_SERVER_URI}/user/profile`,{
                    method: "GET",
                    headers: {
                        "Content-Type": "application/json",
                        "Authorization": `Bearer ${userToken}`,
                    },
                });

                const data = await res.json();
                if (res.ok) {
                    setUserData(data);
                }
            } catch (err) {
                console.error(err);
            }
        }
    
        if (userToken) {
            fetchData();
        }

    }, [userToken]);

    return userData;
};

export default useUserData;

When I log the user object, the profile object is also present. The problem arises as soon as I log the profile object.
I have checked the API and it is working fine. I think there is some issue with my useEffect implementation.
Any help is greatly appreciated.

2

Answers


  1. Try using

    const user = await useUserData()
    

    or

    const data = await user.profile
    

    Also log the user and see what you get.

    console.log(user)
    
    Login or Signup to reply.
  2. You need to get to know how React renders your component, basically it re-renders each time component’s state changed. Here is the flow from your component + hook:

    • First of all, your component renders with state userData = null which is the init value for the state which means const user = useUserData(); the user object is null in this case and where you encountered the issue
    • Once the endpoint returns the value for you and you already set the new state userData, the user object is becoming an object that you need which is a defined object

    As a result of that, you need to handle the case that user can be null such as:

    if (!user) {
       // show loading state
       return <Loading />
    }
    
    // now display the user information
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search