Reputation: 749
I am able to get the value out when I use {userProfile.displayname} and {userProfile.emailacct} which is Batman and [email protected].
So when I try to count number of reviewers {userProfile.reviewers.length} in the h6 tag, it says "Cannot read property 'length' of undefined". But when I tried this {userProfile.reviewers}
, it printed out "5fc519fd1849413ffb6e3ee35fbb3879e8902d14f8c60448"
I don't get it. What am I missing here? Many thanks in advance and greatly appreciated.
The data below is the console.log(result.data.user) in the useEffect()
displayname: "Batman"
emailacct: "[email protected]"
reviewers: (2) ["5fc519fd1849413ffb6e3ee3", "5fbb3879e8902d14f8c60448"]
id: "5fb35251888e8d081c06a7fa"
const[userProfile,setUserProfile] = useState([])
useEffect(()=>{
Axios.get(`http://localhost:5000/api/user/user/${userid}`, {withCredentials:true}).then(result => {
setUserProfile(result.data.user)
console.log(result.data.user)
})
},[])
<h2>{userProfile.displayname}</h2>
<h4>{userProfile.emailacct}</h4>
<div style={{display:"flex",justifyContent:"space-between",width:"120%"}}>
<h6>{userProfile.reviewers} reviewers</h6>
</div>
</div>
Upvotes: 1
Views: 45
Reputation: 202605
userProfile
initial state is an empty array []
, so userProfile.reviewers
is undefined. Any userProfile.XXX
will be undefined. You can't access properties of undefined.
Provide valid initial state to match what is accessed on the initial render.
const[userProfile,setUserProfile] = useState({
displayname: null,
emailacct: null,
reviewers: [],
id: null,
});
You may want to also implement some conditional rendering to wait until the data has been fetched.
Upvotes: 2