React Native: Component does not find state data after setState

Asked

Viewed 168 times

-1

I’ve had this problem for weeks: I am using React Hooks to request an internal api using useEffect to make a request and then store the result within a setState. If I give a console.log the first result and array [ ] (empty) and then an array with the expected information, when I try to render inside a<Text>{user.name}</Text> gives error below.

Typeerror: Typeerror: null is not an Object (evaluating 'user.name')

const [user, setUser] = useState([])
...
useEffect(() => {
 async function loadUser(){
   const response = await api.get('/user/painel', {
   headers: {user_id}})
   setUser(response.data)
 }
 loadUser();
}, [ ])
...
return(
  <View style={styles.container}>
    <Text>{user.name}</Text>
  </View>
)

2 answers

2


I don’t understand it very well, but why do you play it in an array if it’s a single object? If there are several objects in an array, there is no way to pick up using user.name If it is a single object returning, you do not need to declare this state as array. If it’s a single object, try it this way to see if it goes: { user && user.name }

  • That’s right, the function returns an array and within an object. I was picking up the object, so I couldn’t render {user.name}. The solution was to make a user.map() to render, but as it comes to React Native I used <Flatlist>. Thanks!!!

  • If you have this user’s ID, vc tbm can use the Array.find( ) method to find this user within the array. Ai later you can use it with ' user.name }.

1

This error occurs because it is using an asynchronous request, to work properly try to separate the function outside of the Hooks, so it should work, is to read the returned Array, traverses using the map function.

const [user, setUser] = useState([])
...

async function loadUser(){
  const response = await api.get('/user/painel', 
  {
     headers: {user_id}})
     setUser(response.data)
  }
}
 
useEffect(() => {
  loadUser();
}, []);

...
return(
  <View style={styles.container}>
    {
      user.map(
      Name => {
        return (<Text>Name</Text>);
        }
      )
    }
  </View>
)

Browser other questions tagged

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