Home > Software design >  How do i use this fetched data response?
How do i use this fetched data response?

Time:12-25

I Am using react. I have a fetch setup in an useEffect to grab the data from a database from the backend. It pulls the account and sends it back to the front where i can access it from there.

From the File I want to access the user information i have a console log Console Log of the Data

I want to be able to grab like the firstname, lastname individually and use them in the script. how do i go about that. I did try to console log UserData.user and it gave me this result

Console Log of the New result

However when i went to try to get firstname like userData.user.firstname i was met with an error. Im pretty new to react and pushing myself with things ive never done before to learn and any help would be great

Thank you everyone who does help it means alot

Please note all information in screenshots are fictitious and are just prop data.

EDIT: Code For Both the fetch and trying to access it

errors

CodePudding user response:

This may be because you are trying to read the user information before the api returns the data. so check if the array has data before trying to access it . You can use save navigation to check for undefined or null

UserData.user[0]?.firstname 

CodePudding user response:

Based on your screenshot the data you are getting back is an array of user objects. To access it you will need to use:

userData.user[0].firstname

Note that this will access the first user object in the array - you will likely need checks to ensure the data data exists before accessing it, e.g.:

if (userData.user.length > 0) {
  // Access data as needed
}

CodePudding user response:

user is an array so you can acces like this

userData.user[0].firstname;

it will be better if you update your endPoint to get an object instead, so you can have access and check easier

  • Related