ULPGCstudent
ULPGCstudent

Reputation: 74

Problems with fetch calls with Axios in React

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.

Upvotes: 0

Views: 72

Answers (1)

Yehor Androsov
Yehor Androsov

Reputation: 6152

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

Upvotes: 1

Related Questions