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
Try using
or
Also log the user and see what you get.
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:
userData = null
which is the init value for the state which meansconst user = useUserData();
theuser
object isnull
in this case and where you encountered the issueuserData
, theuser
object is becoming an object that you need which is a defined objectAs a result of that, you need to handle the case that
user
can be null such as: