In Panel.js how can I get data from an API that I wrote in index.js?
Panel.js
index.js
ProfilePanel.js
You can use javascript fetch API
GET example
fetch(`https://jsonplaceholder.typicode.com/posts?key=${key}&results=${results}`)
.then((res) => { return res.json() })
.then((data) => {
console.log(data)
});
})
}
POST example
let key = 'key'
let results = 12;
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers : new Headers(),
body:JSON.stringify({key: key, results: results})//use property short hand here
}).then((res) => res.json())
.then((data) => console.log(data))
.catch((err)=>console.log(err))
you already get the response and you map the response to state 'results'.you can dispaly the data by simply writing "this.state.results"
Related
I'm running parallel requests for a series of fetches. I want to type results as an array of response objects (instead of array of type any) but I'm unsure of how to do this. I googled "how to type response object in Typescript" but didn't get useful hits. Is there a way to type the response object other than manually creating a custom type that has all the properties on a response object? Does Typescript have a special built in type we could use here?
const results: any = [];
fetch(URL, {
headers: {
...
}
})
.then(response => {
results.push(response);
})
.catch(err => {
...
})
const responses = await Promise.all(results);
return responses;
Since I am using node-fetch, I ended up with the following solution.
https://www.npmjs.com/package/node-fetch#class-response
import { Response } from 'node-fetch';
const results: Response[] = [];
fetch(URL, {
headers: {
...
}
})
.then(response => {
results.push(response);
})
.catch(err => {
...
})
const responses = await Promise.all(results);
return responses;
I am trying to send the param name in the Cloud Function managed by Firebase using POST method, I've read quite a few documentation, and no matter what I try it always returns undefined. Also is it safe to use this for sensitive data?
Client-Side
fetch(`https://<<APP-NAME>>.cloudfunctions.net/addCardForExistingCustomer`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
JSON.stringify(body: {'name': 'Name'})
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch(err => console.error(err));
Server-side (Firebase Cloud-Functions)
exports.addCardForExistingCustomer = functions.https.onRequest(async (request, response) => {
let name = await request.body.name
response.json({
response: `${name}`
})
})
I need to get an image using the fetch api. My colleague said that the call to the server should return a base64 string to display the image. The image needs to be authenticated and I cant just use its url. This is what I have:
fetch(`${apiUrl}filestore/${logo.name}`, {
.then(res => console.log(res)
Im not really sure how to get the base64 string. Apparantly im not using fetch right. Here is what is displayed in the console,
![screenshot image][1]
Try to format the res to json. Then check the res.
fetch(`${apiUrl}filestore/${logo.name}`, {
method: 'GET',
headers: {
Authorization: JSON.parse(localStorage.getItem('Hidden'))
? `Bearer ${JSON.parse(localStorage.getItem('Hidden')).access_token}`
: '',
},
})
.then(res => return res.json())
.then(res => console.log(res))
Here is the Link to mdn documentation for Fetch API - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("error", e);
considering your response is of JSON type - Link to find the supported body instances - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Body
Try console.log(typeof response); to find out what your response type is so you can set the body instance in .then(response => response.json() or response.text() etc.,)
Make sure you catch the error too.
Currently, I'm trying to learn how to access data from an API and place it into a div onto my html. I'm using fetch, but I'm not sure where to go after I stringify the data. I want to access the 'Brands' data from the API and place it into my html.
fetch("http://makeup-api.herokuapp.com/api/v1/products.json")
.then(res => res.json())
.then(
(data) => {
JSON.stringify(data)
}
I recommend using this tutorial to learn JavaScript fetch.
Here's a working snippet (although it won't work from SO).
const url = 'http://makeup-api.herokuapp.com/api/v1/products.json';
fetch(url)
.then((resp) => resp.json())
.then(function(data) {
let products = data;
return products.map(function(product) {
console.log(product.brand);
//$("#listOfBrands").append(product.brand); // do as you will
})
})
.catch(function(error) {
console.log(error);
});
<div id="listOfBrands"></div>
I am making an app where I receive data from an API. Once I get this data I want to make another call to the same API with the endpoint that I got from the first call.
fetch(req)
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json)
json.meals.map((obj)=>{
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url,{
method: 'GET',
headers: header
})
fetch(req)
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json);
this.setState((prevState)=>{
recipe: prevState.recipe.push(json)
})
})
})
this.setState(()=>{
return{
data: json
}
})
})
I am making two fetch requests here but the problem is the data from the first response is output after second fetch request. Also the state: data gets set before state: recipe and the components render with the data from state: data.
render(){
return(
<div className="my-container">
<EnterCalorie getData={this.getData}/>
<MealData data={this.state.data} recipe={this.state.recipe}/>
</div>
)
}
How can i make sure both get passed down at the same time?
In line 3 return return response.json() instead of nothing (undefined).
Update:
const toJson = response => response.json()
fetch(req)
.then(toJson)
.then(json => {
this.setState(() => {
return {
data: json
}
})
return json
})
.then((json) => {
console.log(json)
const promises = json.meals.map((obj) => {
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url, {
method: 'GET',
headers: header
})
return fetch(req)
.then(toJson)
.then((json) => {
console.log(json);
this.setState((prevState) => ({
recipe: prevState.recipe.push(json)
}))
})
})
return Promise.all(promises)
})
.then(() => {
console.log('job done')
})
You need to map your array into promises. Then use Promise.all to wait for them the get resolved.
There was parenthesis missing from:
this.setState((prevState)=>{
recipe: prevState.recipe.push(json)
})
A sidenote, this whole stuff should be refactored. You're not going to get far with this code style / code complexity.
fetch(req) // req no1
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json)
json.meals.map((obj)=>{
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url,{
method: 'GET',
headers: header
})
fetch(req) // req no 1 called again
.then((response)=>(
response.json()
)).then((json1)=>{
console.log(json1);
this.setState((prevState)=>{
recipe: prevState.recipe.push(json1)
})
this.setState(()=>{
return{
data: json
})
})
})
})
})
I think you are calling api with same req parameters again in the second fetch call
This is a callback hell, please look for Promise races, and check the all() promise method.