-1

I'm storing data fetched from mongodb through nodejs in a variable like this

axios.post('http://localhost:5000/Users/login',user)
    .then(res=>{
     Userdata=res.data.users
      console.log(Userdata)
      console.log(Userdata._id)
       
    })
    

But I'm unable to access the data in variable in render function here:

if(this.state.loggedin){
  
      return <Redirect to={`/UI/Navbar/Dashboard/${Userdata._id}`}/>
    }

it gives me this error:

TypeError: Cannot read property '_id' of undefined

2 Answers2

0

Both chunks are asynchronous. It is better to wrap async data load with useEffect, explicitly set the state of some top-level component, and propagate logged in user with Context API down to other components.

0

Your render function tries to create a component in spite of the data is noe fetched yet. Thats why it Userdata is undefined. Your Userdata must be a state, when axios has fired, use setState to change Userdata. While Userdata is fetching you have to render something like 'in process...'

Tarukami
  • 1,160
  • 5
  • 8
  • what type of state the variable should be? – Faraz Anwer Aug 06 '20 at 14:16
  • I have tried setting the Userdata in a state but it still does not work – Faraz Anwer Aug 06 '20 at 14:26
  • Userdate must be the same type as what res.data.users returns. I assume it is an array, so you cn set initial state as an empty one []. As for it still does not work - the snippet you show is not enough to find the problem. – Tarukami Aug 06 '20 at 14:58