简体   繁体   中英

Display object with axios in my react native project gives undefined

I was trying to get request data from PHPMyAdmin and then output it on my react native project, and I use response.data.username, and yet I get undefined.

 const getInfo = () => { axios.get("https://luxrealest.com/includes/user_registration.php").then( (response) => { console.log(response.username); setDataInfo(response.data.username + " " + response.data.email); }) } getInfo()
 <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.24.0/axios.min.js" integrity="sha512-u9akINsQsAkG9xjc1cnGF4zw5TFDwkxuc9vUp5dltDWYCSmyd0meygbvgXrlc/z7/o4a19Fb5V0OUE58J7dcyw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Expected

Object {
  "": Object {
    "email": "myke@myke.com",
    "id": "11",
    "username": "myke",
  },
  "1": Object {
    "email": "aisosa.erharuyi11@gmail.com",
    "id": "12",
    "username": "General.Bigman",
  },
  "2": Object {
    "email": "amiatorjay@gmail.com",
    "id": "13",
    "username": "Jaycee",
  },
}

Given the shape of your data you need to iterate over this object like this:

 for (let key in response.data) {
     setDataInfo(response.data[key].username + " " + response.data[key].email);
 }

This of course will call setDataInfo 3 times for your data. If you want only a specific user you will need to add additional logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM