1
When I try to access the full_name property of the user object with useState, the application says that the property is Undefined.
Here is the code:
import React, { useState, useEffect } from 'react'
import api from '../../services/api'
function User(props) {
const [user, setUser] = useState({})
const { id } = props.match.params
useEffect(() => {
async function getUser() {
const response = await api.get(`/users/${id}`)
setUser(response.data)
}
getUser()
}, [id])
console.log(user.repos.full_name[0])
function User() {
return (
<div>
{user.name}
</div>
)
}
export default Use
and here’s the mistake:
index.js:1 The above error occurred in the <User> component:
in User (created by Context.Consumer)
in Route (at Routes.js:13)
in Switch (at Routes.js:10)
in Router (created by BrowserRouter)
in BrowserRouter (at Routes.js:9)
in Routes (at App.js:9)
in App (at src/index.js:5)
Consider adding an error boundary to your tree to customize error handling
behavior.
Visit https://fb.me/react-error-boundaries to learn more about error
boundaries.
I understood yes, thank you very much for the help, I was trying for a long time, I had not attacked myself to this, but I will certainly study more...
– Jean Paulo de Brum
In its component you use the properties of this user without paying attention if it has actually been loaded with the information of the API. This generates these problems with
undefined
.user
. Checking the existence of data in its state before using it is important in asynchronous codes.– Diego Miranda