1

I can access JSON objects in the results here

useEffect(() => {
    fetch(`/user/${userid}`,{
        method:'get',
        headers:{
            "Authorization":`Bearer ${localStorage.getItem('token')}`}

    }).then(res=>res.json())
        .then(result=>{
            console.log(result.user.name) //I can access JSON objects in the results here//
            setProfile(result)
        })
        .catch(err=>console.log(err))

}, [])

I can access JSON while Changing State but it throws errors like UserProfile.user is undefined,UserProfile.posts.length is undefined when rendering JSX. TO access the nested Data I have tried creating more state Variables. It works but the code have become long. I looked for solution in various website but could not find. Any one help me.

return (
    <>
        {
            UserProfile?<div style={{maxWidth:'800px',margin:"0px auto"}}>

                    <div style={{
                        display:"flex",
                        justifyContent:'space-around',
                        margin:"18px 0px"
                    }}>
                        <div>
                            <img style={{borderBottom:"1px solid grey",width:"160px",height:"160px",borderRadius:"80px"}} src="https://images.unsplash.com/photo-1569466896818-335b1bedfcce?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"/>

                        </div>
                        <div>
                            <h4>{UserProfile?UserProfile.user.name:"Loading..."}</h4>

                            <div style={{display:"flex",justifyContent:"space-between",width:"100%"}}>
                                <h6>{UserProfile.posts.length} posts &nbsp;</h6>

                                <button onClick={()=>followUser()} className="btn waves-effect waves-light #64b5f6 blue lighten-2" type="button" name="action">Follow</button>

                            </div>
                        </div>
                    </div>


                    <div className="gallery">
                        {
                            UserProfile.posts.map((item)=>{
                                return(
                                    <img className="item" key={item._id} src={item.photo}/>
                                )

                            })

                        }
                    </div>
                </div>:
                <h1>Loading:</h1>

        }
    </>
)

export default Profile
3
  • What is your initial state? Commented Jul 19, 2020 at 8:41
  • What’s the shape of the object? Commented Jul 19, 2020 at 8:57
  • I'd keep all the local variables beginning in lowercase: userProfile, not UserProfile. Remember that uppercase plays a special role in React/JSX. Moreover, I suspect you're using setProfile as setter for userProfile: React guidelines recommends to follow the rule: userProfile - setUserProfile. Commented Jul 19, 2020 at 8:57

2 Answers 2

1

Based on the code and your inputs, the problem may be because you are trying to access the variables before they are accessible.

As you are making async API call in useEffect() it may take some time before you get data. But, as you are accessing the data before you even get it errors like 'UserProfile.user is undefined', 'UserProfile.posts.length' is undefined will occur'

To avoid such errors make sure you add a check as shown below

        <>
           {
              UserProfile && 
                <div style={{maxWidth:'800px',margin:"0px auto"}}>
                    <div style={{
                        display:"flex",
                        justifyContent:'space-around',
                        margin:"18px 0px"
                    }}>
                        <div>
                            <img style={{borderBottom:"1px solid grey",width:"160px",height:"160px",borderRadius:"80px"}} src="https://images.unsplash.com/photo-1569466896818-335b1bedfcce?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60"/>
         
                        </div>
                        <div>
/* -----> modify it here*/  <h4>{UserProfile ? UserProfile.user && UserProfile.user.name:"Loading..."}</h4>
         
                            <div style={{display:"flex",justifyContent:"space-between",width:"100%"}}>
/* -----> modify it here*/  <h6>{UserProfile && UserProfile.posts && UserProfile.posts.length} posts &nbsp;</h6>
                 
                            <button onClick={()=>followUser()} className="btn waves-effect waves-light #64b5f6 blue lighten-2" type="button" name="action">Follow</button>
                            
                        </div>
                        </div>
                        </div>
                       
                        
                        <div className="gallery">
                            {
                              UserProfile.posts.map((item)=>{
                                 return(
                                  <img className="item" key={item._id} src={item.photo}/>
                                 )
                              })
                            }
                        </div>
                </div> 
                :
                <h1>Loading:</h1>
             }
        </>
Sign up to request clarification or add additional context in comments.

Comments

0

I got the solution for this. I got rid of this problem by setting initial state to null. Thank You for answering my query.

//my initial useState declaration//
const [userProfile,setUserProfile]=useState([])
//Solution//
const [userProfile,setUserProfile]=useState(null)


I am new to react so I got into problem.

1 Comment

Having a very similar problem, describe here. Tried your solution, but it didn't work for me. What did work was to assign the nested element I wanted somewhere.down.the.line to another var (or const) and then referenced that. This is a kluge at best. I'd really like to understand why nested objects like this don't seem to work when fetched. Cheers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.