Property coming as Undefined?

Asked

Viewed 92 times

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.
  • 1

    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...

  • 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.

1 answer

2


Enough people come up with the same doubt, in your case on props information does not have a local state so your code in the array of useEffect can be without any item, so that it is executed in the creation of the component, example:

import React, { useState, useEffect } from 'react'
import api from '../../services/api'

function User(props) {
    const [user, setUser] = useState(null);
    useEffect(() => {
        const { id } = props.match.params
        async function getUser() {
            const response = await api.get(`/users/${id}`)
            setUser(response.data)
        }
        getUser()
    }, []); 
    if (user) {
        return (
            <div>
                {user.name}
            </div>
        )
    } else {
        return (<div>Carregando ...</div>);
    }
}

export default User

Your code also has conceptual errors, need to give a read in the documentation, but, I think with my changes solve and remove your doubts, I did not understand why you called the class within itself, certainly lack to give a studied.

Another example:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.