Why Am I Getting Undefined as an Answer When Fetching Data from an API

Why am I getting undefined as an answer when fetching data from an api?

The data of second .then is an array with a object inside.
If you want to get quote in the object, you need to use data[0] to select the object.Then, use .quote to select the key quote in the object. And you can get the value you want.

let button = document.querySelector('#button');
let quote = document.querySelector('#quote');

function getInfoFetch(){
fetch('https://thesimpsonsquoteapi.glitch.me/quotes')
.then(response => response.json())
.then((data) => {
console.log(data);
//this is an array with object(index = 0) inside [{...}]
quote.innerText = data[0].quote;
})
.catch(err => console.log(err));
}

button.addEventListener('click', getInfoFetch);

Why I am getting undefined while fetching data form API

The data object returns in an array, so you have to get the 0th element to then access the object and its data. Like this:

fetch(`https://api.unsplash.com/photos/random/?client_id=YILDy9SO8bXBp_dwX7aFO3R_UAs1-8v0gTrK2o2wllE&count=1`)
.then(response => response.json())
.then(data => {
console.log(data);
console.log("Likes:", data[0].likes);
console.log("Views:", data[0].views);
console.log("Downloads:", data[0].downloads);
});

Why is my response data undefined when sending a fetch()?

The then method takes a callback. That callback returns a value.

If that value is a promise, then it will be adopted and when it is resolved, then next then function will recieve the resolved value of that promise.

If that value isn't a promise then the next then function will recieve that value.

This is your function:

res => console.log(res)

It returns the return value of console.log(res).

console.log always returns undefined

So the next then function:

data => console.log(data)

… gets undefined passed into data.


You need to return the value you actually care about.

If that value is the data in the response body, then you need to:

  1. Get that data out of the body
  2. Return it from the function

For example:

.then(res => {
console.log(res);
return res.json();
})
.then(data => console.log(data))

This assumes that you get JSON back from the body. There are other methods for other kinds of data.

Fetched Json data from API is undefined

setProduct(response.data[0]) is an asynchronous method and hence the console would give undefined when trying to see the value in product through console log. If you really want to see the response from api or if the product is getting set in state. You can try the below code.

import React,{ useEffect, useState } from 'react'
import { MessageElement } from './Elements'
import { useParams} from "react-router-dom"
import axios from 'axios'

function DetailProductPage() {

const productId = useParams().productId


const [product, setProduct] = useState([])
const URL = `http://url/api/products/${productId}`

useEffect(() => {
axios.get(URL)
. then((response) => {
console.log('response from api', response);
setProduct(response.data[0])

});
}, [])
console.log("product set in state", product)
return (

<MessageElement>Detail Page</MessageElement>
)
}

Fetch API returning "undefined"

The promise .then methods can be chained in a way each chained then methods will receive the returned value of the previous one. In your case, the first one does not return any values, making the second one receiving nothing, also well known as undefined.

As the url your code is calling return json content, you should return after loging success the result of res.json().

This will read the stream of the response body and parse it as json, using a promise.

fetch result from API returns undefined

Make it simple with async/await syntax.

Avoid mixing async/await with then/catch style.

const getDataResponses = await Promise.all([
fetchClient.getData(
getEndpoint(
`amount=${countValues[0]}&difficulty=easy&type=${questionType}`
)
),
fetchClient.getData(
getEndpoint(
`amount=${countValues[1]}&difficulty=medium&type=${questionType}`
)
),
fetchClient.getData(
getEndpoint(
`amount=${countValues[2]}&difficulty=hard&type=${questionType}`
)
),
]);

const data = await Promise.all(
getDataResponse.map((response) => {
return fetchClient.processData(response, "results");
})
);

console.log('getDataResponses', getDataResponses);
console.log('processDataResponse', data);
return [...data[0], ...data[1], ...data[2]];

Undefined parameter in react function when retrieving data from API

In React state updates are asynchronous in nature, so because of this you cannot expect updated state values immediately on the next line after calling state update(setState).

In your case on button click, you are doing this -

<button
onClick={(e) => {
// this will change state value for playerData
searchForPlayer(e);
// but here on next line you cannot access updated value
// because searchForPlayer will not run synchronously
var a = playerData.id;
console.log(a); // so you will mostly get undefined here
searchPlayerData(a);
}}>
Search Player
</button>
  1. To fix this either you need to use useEffect with dependency array with playerData like this -
React.useEffect(() => {
if(playerData.id){
//call next function or api here
}
}, [playerData])

Above useEffect will get called when your playerData gets changed. So in here, you can call anything which needs state playerData.


  1. Or if you only need to call searchPlayerData after searchForPlayer then instead of using the state to store playerData and then passing it to searchPlayerData you can directly call searchPlayerData inside .then in searchForPlayer, see below code -
function searchForPlayer(event) {
var APICallSummoner =
"https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/" +
searchText +
"?api_key=" +
API_KEY;

axios
.get(APICallSummoner)
.then(function (response) {
// you do not need to set below state value
// if you are not going to use it other than calling next api
setPlayerData(response.data);
if(response.data){
//calling next function here
searchPlayerData(response.data.id);
}
})
.catch(function (error) {
console.log(error);
});
}



Related Topics



Leave a reply



Submit