I am the new guy in the JS and reactJS.
I want to get info from API to an array. I made API that show all the info from my DB.
It looks like this :
const [tempNew, setTempNew] = useState([]);
const getAllWeatherCelsius = () => {
fetch('http://localhost:5000/weather')
.then(response => {
return response.json();
})
.then((jsonData) => {
let tmpArray = [];
for (var i = 0; i < jsonData.length; i++) {
tmpArray.push(jsonData.dayCelsius[i]) <---- here is the error
}
setTempNew(tmpArray);
})
}
Im want to collect all values from "dayCelsius" line into array.
What i need to change in this code ? Thank you :)
Can you provide more info about the error? But You can try using the map function like
const tmpArray = jsonData.map(r => r.dayCelsius);
You can use map function to return the dayCelsius value of each element and store them in the tmpArray.
let tmpArray = jsonData.map((el, i) => el.dayCelsius);
So, what I understand is that you are facing difficulty in just getting the dayCelsius value from the array of objects you fetch from your API.
It is difficult to make out what the problem is as more info about the error is required to see what is going wrong.
What I have done differently here is instead of the for-loop and jsonData.dayCelsius[i], I have used data.map((r,e) => r.dayCelsius).
const [temp, setTemp] = useState([]);
const getAllWeatherCelsius = () => {
fetch('http://localhost:5000/weather', {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
}
})
.then(response => {
return response.json();
})
.then((data) => {
const tempArray = data.map((r,e) => r.dayCelsius);
setTemp(tempArray);
})
.catch(err => console.log(err));
}
I hope it helps you, have a good day :)
Related
I am trying to get data from my front-end and store it in backend, however everytime I try to return it I receive `{ name: '' } in the terminal instead of the name I have inserted.
I have also tried to use Inspect Element to tell me where the error arises but it's not helping me as much.
Have attached my code below.
The code seems to cancel out the second "name" when I try to fetch data from localhost.
Any ideas. I have also attached screenshot for further clarity.
Thanks!
document.addEventListener('DOMContentLoaded', function () {
fetch('http://localhost:5001/getAll')
.then(response => response.json())
.then(data => loadHTMLTable(data['name']));
});
const addButton = document.querySelector('#add-name-button');
addButton.onclick = function () {
const nameInput = document.querySelector('#name-input');
constname = nameInput.value;
nameInput.value = '';
fetch('http://localhost:5001/insert',{
headers:{
'Content-type': 'application/json'
},
method: 'POST',
body: JSON.stringify({ name : name })
})
.then(response => response.json())
.then(data => insertRowIntoTable(data['data']));
}
function insertRowIntoTable(data){
}
function loadHTMLTable(data) {
const table = document.querySelector('table tbody');
console.log(data);
if (data.length === 0){
table.innerHTML = "<tr><td class = 'no-data' colspan = '5'> No Data </td></tr>";
}
}
constname = nameInput.value; should be const name = nameInput.value;
You should be using 'use strict' to avoid such errors(?) or a more advanced tools like linting etc.
how to consume from one api with another api.
var url_1 = 'https://dog.ceo/api/breeds/list/all';
fetch(url_1)
.then( response => response.json())
.then(data => {
const breeds = data.message;
var arr = [];
for (var b in breeds) {
arr.push({
breed : b,
subBreeds : [
breeds[b][0]
],
images : [{
url: ''
}]
})
}
I also have this other api, from where I extract the images of each breed of dog, but here you need the variable that would be the name of the dog's breed.
var url_2 = 'https://dog.ceo/api/breed/{breed_name}/images';
fetch(url_2)
.then( response => response.json())
.then(data => {
const images = data.message;
var arr_images = [];
for (var i in images) {
arr_images.push({
images : [{
url: images[i]
}]
})
}
So what I don't know, how can I join to send the name of the dog's breed to the second api to consume it?
And how can I join the arrangement of the images with the arrangement above?
it should be something like this
{ "breed": "Hound",
"subBreeds": [
"subBreedA",
"subBreedB",
"subBreedC"
],
"images":[
{"url":"http://some.url.com"},
{"url":"http://some.other.url"}
]
}
I hope I have been clear, thanks for your help, I will be very grateful.
I would split it up into separate functions so that you can focus on one part at a time. Then, combine them to get all of the data that you want. In this way, you can also re-use each function in case you want to use the data in a different way:
TS Playground
// dog.ceo API
async function fetchDogApiResult (apiPath) {
const response = await fetch(`https://dog.ceo/api/${apiPath}`);
if (!response.ok) throw new Error(`Response not OK (${response.status})`);
const data = await response.json();
if (data.status !== 'success') throw new Error('Response not successful');
return data.message;
}
async function fetchBreeds () {
return fetchDogApiResult('breeds/list/all');
}
async function fetchSubBreeds (breed) {
return fetchDogApiResult(`breed/${breed}/list`);
}
async function fetchImages (breed, subBreed) {
return fetchDogApiResult(`breed/${breed}${subBreed ? `/${subBreed}` : ''}/images`);
}
async function fetchDogData () {
const breeds = await fetchBreeds();
return Promise.all(Object.entries(breeds).map(async ([breed, subBreeds]) => ({
breed,
subBreeds,
images: (await fetchImages(breed)).map(url => ({url})),
})));
}
(async () => {
const dogData = await fetchDogData();
console.log(JSON.stringify(dogData));
})();
You can use async/await for call second api in second then of first api, after you get data from second api, you can use for loop for them. like this
var url_1 = 'https://dog.ceo/api/breeds/list/all';
fetch(url_1)
.then( response => response.json())
.then(async data => {
const breeds = data.message;
const resUrl2 = await fetch(url_2)
const dataUrl2 = await resUrl2.json()
var arr = [];
for (var b in breeds) {
arr.push({
breed : b,
subBreeds : [
breeds[b][0]
],
images : [{
url: ''
}]
})
}
const images = dataUrl2.message;
var arr_images = [];
for (var i in images) {
arr_images.push({
images : [{
url: images[i]
}]
})
}
})
I have a json file and i fetched the data. However I cannot display it on the screen.
How can I display ? I get the data results in the console however I cannot reach the parametres like product name, price.
My code is below
index.html
<body>
<div id="products"></div>
<script src="/index.js"></script>
</body>
index.js
fetch("./data.json")
.then(response => {
return response.json();
})
.then(data => console.log(data));
showProducts = products => {
const showProductsDiv = document.querySelector("#products");
products.map(product => {
const productElement = document.createElement("p");
productElement.innerText = `product Name: ${product.name}`;
showProductsDiv.append(productElement);
});
}
I also share console results
You need to use your showProducts function.
Here is a sample code that will work for you too, but please, bear in mind, that I have used an example api. It's a bit different to yours that is why I have results array and name.first.
const url = 'https://randomuser.me/api/?results=10';
fetch(url)
.then((resp) => resp.json())
.then(data => {
return showProducts(data)
})
showProducts = products => {
const showProductsDiv = document.querySelector("#products");
products.results.map(product => {
const productElement = document.createElement("p");
productElement.innerText = `product Name: ${product.name.first}`;
showProductsDiv.append(productElement);
});
}
I'm trying to use Spotify API and to move into the Arrays.
const App = () => {
const [isLoading, setIsLoading] = useState(true);
const [dataSource, setDataSource] = useState();
useEffect(() => {
return fetch("https://api.spotify.com/v1/me/albums?offset=0&limit=5", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization:
"Bearer AUTH CODE "
}
})
.then(response => response.json())
.then(responseJson => {
setIsLoading(false);
// console.log(responseJson);
// let result = Object.values(responseJson); // if I want to convert it in array
let result = responseJson
setDataSource(result);
});
}, []);
console.log(dataSource);
and I get an object
{href: "https://api.spotify.com/v1/me/albums?o`enter code here`ffset=0&limit=5", items: Array(5) ...}
I would like to go into items but when i do
console.log(dataSource.items);
or
console.log(dataSource.items[1]);
I get
Cannot read property 'items' of undefined
Any idea?
Where is my mistake?
The dataSource state is by default undefined, you need to change the default value to have items property. The fetch is handling the then asynchronously so the data will arrive few milliseconds later and in that time the code tries to access items property which is missing.
You can try to initialize differently, like the following:
const [dataSource, setDataSource] = useState({ items: [] });
I hope this helps!
I would like to add title to my JSON object, the structure I wish to achieve is:
{
"posts": [
{
"title": "put title here",
"upvotes": 1234,
"score": 1000,
"num_comments": 100,
"created": "16.05.2019 12:12",
},
]
}
I was able to fetch data and put it into array of 26 elements, everything is fine but I wish to somehow add this "posts:" to be above whole rest, here is my code:
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json()
.then(async res => {
let posts = await res.data.children.map(el => {
let title = el.data.title;
let upvote = el.data.ups;
let score = el.data.score;
let comments = el.data.num_comments;
let created = el.data.created;
const allPosts = {title, upvote, score, comments, created}
postList.push(allPosts)
return postList
})
console.log(posts);
return posts
})
You might need to create the object like below
{propertyName:value}
const allPosts = {title:title,upvote: upvote,score: score,comments: comments, created:created}
postList.push(allPosts)
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json())
.then(async res => {
console.log(res);
let posts = await res.data.children.map(el => {
let title = el.data.title;
let upvote = el.data.ups;
let score = el.data.score;
let comments = el.data.num_comments;
let created = el.data.created;
const allPosts = { title, upvote, score, comments, created };
let postList = [];
postList.push(allPosts);
return postList;
});
console.log({"posts": posts});
return {"posts": posts};
});
You can try out the following code.
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json())
.then(res => ({
posts: res.data.children.map(el => ({
title: el.data.title,
upvote: el.data.upvote,
score: el.data.score,
comments: el.data.num_comments,
created: el.data.created
}))
}))
.then(posts => {
console.log(posts);
});
You can do it in this way:
fetch("https://www.reddit.com/r/funny.json")
.then(resp => resp.json()
.then(async res => {
let posts = await res.data.children.map(el => {
return {
title: el.data.title,
upvote: el.data.ups,
score: el.data.score,
comments: el.data.num_comments,
created: el.data.created
}
})
const postObject = { posts }
console.log(postObject);
return postObject
})
Map function return value, in this way you get an object with key (posts) and values (an object with details).