0

I am trying to use the https://api.randomuser.me/ API to get the data from a person. As for now, I am trying to get only his first and second names, and date of birth, but I don't know if I am doing the call to the API wrong or what I am doing incorrectly. This is the code I have:

import Axios from 'axios'
import { useState } from 'react';

function FetchCall() {
  
  const[name,setName] = useState("")
  const[birth,setBirth] = useState("")

  const getInfo = () => {
  Axios.get("https://api.randomuser.me/").then(
    (response) => {
      setName(response.results.name.first + " " + response.results.name.last);
      setBirth(response.dob.date);
    }
  );
};

  return(
    <div>
      Hello 
      <button onClick={getInfo}>Get User</button>
      {name}
      {birth}
    </div>
  );
}

export default FetchCall;

I am getting a "Unhandled Rejection (TypeError): Cannot read property 'name' of undefined" error when clicking on the button.

1 Answer 1

1

Axios response stores response json in .data field

response.results should be changed into response.data.results

Also, just a note, results is an array, so you need to apply indexer as well. For example, response.data.results[0].name.first

Check out React dev tools to set breakpoints and find which item in sequence is undefined

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.