How to Fetch specific api from database? - mysql

componentDidMount() {
fetch("http://localhost:5000/customers/:id")
.then((res) => res.json())
.then((info) => {
this.setState({ info });
})
.then((err) => console.log(err));
}
How to fetch a specific data from database by sending the required ID with URL?

You can use the format string syntax from javascript and add the id to the url-string with that.
const id = 42
fetch(`http://localhost:5000/customers/${id}`)

Related

how to get data from fetch to a variable?

so i'm fetching this api using the fetch
fetch("https://public-api.solscan.io/transaction/"+JSON.parse(message.data).params.result.value.signature)
.then(response => response.json())
.then(response => console.log(JSON.stringify(response.parsedInstruction[1].params.mint)))
.catch(error => nothing());
but i need
JSON.stringify(response.parsedInstruction[1].params.mint
in a variable so i can make another api request please help me
this is the code where i want to use with the variable
const mintAddress = new PublicKey("7brV5ykCzriKhVhj99kav97LQQrpb18J3kMonGxveML2");
const nft = await metaplex.nfts().findByMint({ mintAddress }).run();
const png = nft.json.image ;
console.log(nft.json)

Handling Deeply nested Json Objects using useState in Reactjs

Am trying to get value from nested json. but got 'undefined' error. when i display the same object in console, it works fine. I want to fetch particular field from nested json object.
here is the json output from api, i want to fetch userid, name and verified fields from below json
{
status: true,
user:
{
id: 11362
phone: "+918971557357"
name: "Sagar pawar"
email: null
bio: null
address: null
date_of_birth: null
token: "EMAWdBl3LDjl1X5veo6VvZBKfgQns5wTFXKWjIh9w4VKKXlclRo5ZBlWaJUBS5ImaVZANN9DlHSbFWquObaW1FIJLVGPqFLWKoPEzKLvZAJakhoTxg5TRTjVtLEVz9R9zAbocwF7dmRdI4GCAMlJdtKOEZAUuOcf6AZD"
image: ""
role: "user"
notification_cleared: {date: "2019-12-28 11:42:34.899503", timezone_type: 3, timezone: "UTC"}
deleted_by: null
blocked: 0
verified: 0
}
}
and this is the fetch function i tried.
fetch(url, options)
.then(res => res.json())
.then(body => console.log("Data Response", body))
.then(data => {
const jsonobj = data.user.id;
console.log("User ID:", jsonobj);
})
and this one i have tried.
const [responseUserId, setUserId] = useState(userId);
...
fetch(url, options)
.then(res => res.json())
.then(res =>
setUserId({ userId: res.user['id'] })
)
thanks in advance.
First and foremost. In your fetch function when you log data, in the second then you don't return any data, so in the third then your callback argument is undefined. After console.log("Data Response", body), you should add return body, so it get's passed down as data in your next then statement.
Second, your id is a string(or number, it doesn't matter). So your responseUserId will be a string. So when setting the state with useState you don't need to pass in an object, just pass the value. Like this : setUserId(res.user['id'])
Hope this helps!
i create a simple fetch request and setUserId just like you want and it works.
the problem is you use 3 then methods you only need 2.
in the third then data is undefind but in second you have what you need.
.then(res => res.json())
.then(body => console.log("Data Response", body))
.then(data => {
https://codesandbox.io/s/reverent-mestorf-o43s1
it is so simple i hope it help you
I will use your last example of a functional component with useState:
You initialize responseUserId with userId. Given the code you provided, that should fail to compile, because userId is not defined. Give it a value, like null, or 0 or an empty string.
If you return an object with only one property, you probably don't need the object data type. In my example data.userId and consequently responseUserId is of type Number.
import React, { useEffect, useState } from 'react';
export default function App() {
const [responseUserId, setResponseUserId] = useState(null);
useEffect(() => {
const url = 'https://jsonplaceholder.typicode.com/todos/1';
fetch(url)
.then(res => res.json())
.then(data => setResponseUserId(data.userId))
.catch(err => console.error(err));
}, []);
return responseUserId && <h3>{responseUserId}</h3>;
}

How to randomly fetch from a JSON file and render it into a FlatList?

I have an app which fetch data from a JSON file. The problem is, it fetches the data from top to bottom. I want it to fetches randomly within the JSON file. How would I achieve this?
This is how I fetch the JSON:
componentDidMount() {
const url = ''
this.setState({ isLoading: true });
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson.product,
dataBackup: responseJson.product,
isLoading: false
});
})
.catch((error) => {
console.log(error)
})
}
When you're reading a file there is no way to change the order of content.
However, once the json is parsed, since your product key is an array, you can shuffle this array when you setting the state.
You can use the shuffle function from this answer
How to randomize (shuffle) a JavaScript array?
Alternatively if you're using lodash, there is shuffle function for collections :
https://lodash.com/docs/4.17.14#shuffle
Your final code would be:
// import shuffle function from linked anwser,
// or with lodash :
import { shuffle } from "lodash";
// ...
componentDidMount() {
const url = "";
this.setState({ isLoading: true });
fetch(url)
.then(response => response.json())
.then(responseJson => {
this.setState({
dataSource: shuffle(responseJson.product),
dataBackup: responseJson.product,
isLoading: false
});
})
.catch(error => {
console.log(error);
});
}

how to access nested data by nesting fetch calls?

I'm having trouble understanding the best approach to this.
My goal is to display nested data.
I use fetch on this url - https://horizons-json-cors.s3.amazonaws.com/products.json
which takes me to a page that contains json. inside the json is 3 urls. each url contains the data that I need to get to.
So far, I've accessed the first layer, and now have an array of the item urls. I guess I don't understand how to fetch the data while im inside the outter fetch call.
Here's my code thus far (the result is an array of urls, where each url contains the data I need.) :
componentDidMount() {
console.log('Fetch');
fetch("https://horizons-json-cors.s3.amazonaws.com/products.json")
.then((resp) => (resp.json()))
.then((json) => {
var productUrlArr = [];
for (var i = 0; i < json.length; i++) {
productUrlArr.push(json[i].url);
}
.catch((err) => {
console.log('error', err);
});
}
If you guys could help me out and really walk through how to access the next level of data, I would really, really appreciate it.
You can Fetch Data for Inner URLs this way too,
// 1. Outer Fetch call initiated here
fetch("https://horizons-json-cors.s3.amazonaws.com/products.json")
.then(res => {
return res.json()
})
.then(res => {
// 2. array for storing url's retrieved from response
var urlArray = []
if (res.length > 0) {
// 3. Push url inside urlArray
res.map(data => urlArray.push(data.url))
}
// 4. an array of urls
return urlArray
})
.then(urls => {
// Return an promise which will return "JSON response" array for all URLs.
// Promise.all means “Wait for these things” not “Do these things”.
return Promise.all(urls.map(url => {
// Take url fetch response, return JSON response
return fetch(url).then(res => res.json())
}
))
})
.then(res => {
// Store all objects into array for later use
var objArr = res; return objArr
})
//.then(...)
You have a little error in your code.
It's missing }) before .catch
With it you can use your data in the array.
componentDidMount(){
console.log('Fetch');
fetch("https://horizons-json-cors.s3.amazonaws.com/products.json")
.then((resp) => (resp.json()))
.then((json) => {
var productUrlArr = [];
for (var i = 0; i < json.length; i++) {
productUrlArr.push(json[i].url);
}
console.log(productUrlArr);
}).catch((err) => {
console.log('error', err);
});
}
Hope it helps.
It simple. First get all the url first like you did. Then map and pass it into Promise.all.
fetch("https://horizons-json-cors.s3.amazonaws.com/products.json")
.then((resp) => (resp.json()))
.then((json) => {
Promise.all(json.map(product =>
fetch(product.url).then(resp => resp.text())
)).then(texts => {
// catch all the data
})
}).catch((err) => {
console.log('error', err);
});

Ionic 2 - Passing ID from json to child (details) page

I have a provider service that calls get requests from my API. I then have a listing page whereby you can scroll though many recipes. What I am struggling with is taking the ID of each recipe and passing it to the details page as this needs to be included within.
My service request is for the listing is
loadCategory1() {
var url = "http://api.yummly.com/v1/api/recipes?_app_id=////&_app_key=////";
if (this.Category1) {
return Promise.resolve(this.Category1);
}
return new Promise(resolve => {
this.http.get(url + "&allowedAllergy[]=396^Dairy-Free&allowedAllergy[]=393^Gluten-Free&maxResult=50&start=10")
.map(res => res.json())
.subscribe(data => {
console.log(data);
this.Category1 = data.matches;
resolve(this.Category1);
});
});
}
and I currently have a separate one for my details as well
loadDetails() {
if (this.details) {
return Promise.resolve(this.details);
}
return new Promise(resolve => {
this.http.get('http://api.yummly.com/v1/api/recipe/French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364?_app_id=//////&_app_key=//////')
.map(res => res.json())
.subscribe(data => {
console.log(data);
this.details = data;
resolve(this.details);
});
});
}
As you can see in the details request i have French-Onion-Soup-The-Pioneer-Woman-Cooks-_-Ree-Drummond-41364 This needs to be dynamic by taking the ID from each recipe. Example is below.
Within each .ts file I have the following
loadRecipes(){
this.apiAuthentication.loadCategory1()
.then(data => {
this.api = data;
});
}
This allows me to call the request.
I'm at the point now where I have no clue what to do so some help would be great.
Your DetailsService can be something like this:
loadDetails(detailsId: string) {
return new Promise(resolve => {
this.http.get('http://api.yummly.com/v1/api/recipe/'+detailsId+'?_app_id=//////&_app_key=//////')
.map(res => res.json())
.subscribe(data => {
console.log(data);
this.details = data;
resolve(this.details);
});
});
}
Navigate to DetailsPage with arguments:
this.navCtrl.push(DetailsPage,{
recipe: recipe
});
And you can call DetailsService inside DetailsPage by using code like this:
loadDetails(){
this.apiAuthentication.loadDetails(this.recipe.id)
.then(data => {
this.details = data;
});
}