ReactJS fetch data from custom API and render data - json

I am currently working on a ReactJS project where I created my own JSON-api. I am trying to fetch a specific value in the array but all I get back is undefined, console.log gives me this: Array.
My fetch function is as follows:
_fetchData = async () => {
const response = await fetch('http://localhost:3000/stories');
const json = await response.json();
this.setState({
title: json.title,
thumbnail_img_url: json.thumbnail_img_url
});
}

Please learn basic programming first.
gives me this: Array.
You yourself said json is an array and trying to access its property with json.title. Please either use the first element of the array or revisit your flow and see what you actually want to do.
_fetchData = async () => {
try {
const response = await fetch('http://localhost:3000/stories');
const json = await response.json();
this.setState({
title: json[0].title,
thumbnail_img_url: json[0].thumbnail_img_url
});
catch (err) { console.error(err.toString()); }
}

Related

Is there a way to get a nested JSON object using react native?

My JSON file can be found using this link. The object "features" have a nested object called "properties", where I want to access the data from that object. I've tried to use the useEffect() hook from React and implemented that in the code below. I tried to get the "properties" sub object by implementing the following code: data.features.properties, but that returns undefined. What code am I implemented wrong or what logic is incorrect?
useEffect(() => {
fetch('https://www.vaccinespotter.org/api/v0/states/' + stateAbb + '.json')
.then((response) => response.json())
.then((json) => {
setData(json);
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, [stateAbb]);
stateAbb is the state abbreviation for the state that the user selects in a text input on a different screen. propData seems to store the "features" object as I have used the alert() function and typeof() to determine that propData is an object.
I've tried to JSON.parse() and implemented some other StackOverflow answers, such as this and this. The effect still remains the same. data.features works as an object but data.features.properties returns undefined.
Any help would be appreciated!
Thanks!
React hooks doesn't allow async await in useEffect so you can create new function like this
useEffect(()=>{
fetchData()
},[])
const fetchData = async ()=>{
try{
const response = await fetch('https://www.vaccinespotter.org/api/v0/states/' + stateAbb + '.json')
const json = await response.json()
console.log(json); // your data is here!
}catch(err){
console.log(err)
}
}

Data fetch from JSON file

I am trying to fetch data from external JSON and I was able to console.log it, so the fetch works, but I am having trouble to print the values.
JSON:
{
"data": {
"shoes": [
{
"types": [
{
"color": "pink",
}]
}]
}
I need to get access to the color (pink).
This is my fetch:
const shoesInformations = "json.url"
const [shoesData, setShoesData] = useState([]);
useEffect(() => {
getShoesInfo();
}, []);
const getShoesInfo = async () => {
try {
const response = await fetch(shoesInformations);
const jsonData = await response.json();
const { data } = jsonData;
setShoesData(jsonData);
console.log(data);
} catch (err) {
console.log(err);
}
};
And my attempt to print it:
<p>{shoesData.types.color}</p>
I do not need to map through the data just print the value one by one {shoesData.types.color[1]}
The main problem is that you assign the whole fetch response instead of only the shoes array within it to the shoesData state variable. Try this:
const [shoesData, setShoesData] = useState([]);
useEffect(() => {
getShoesInfo();
}, [getShoesInfo]);
const getShoesInfo = async () => {
try {
const response = await fetch(shoesInformations);
const jsonData = await response.json();
setShoesData(jsonData.data.shoes);
} catch (err) {
console.log(err);
}
};
and then when you want to present it first add a check for empty array or use the safe navigation operator. Either do (if you really want it hardcoded):
<p>{shoesData[0]?.types[0].color}</p>
<p>{shoesData[1]?.types[0].color}</p>
or more flexibly something like:
const getShoesRepresentation = () => {
if (shoesData.length > 0) {
return null;
}
else {
return (
<p>{shoesData[0].types[0].color}</p>
);
}
};
and then use {getShoesRepresentation()} in your rendering. This will handle the empty array case and you can extend it to handle iteration over all shoe objects that you need. I strongly suggest you use an iteration approach instead of hard-coding the data like that. You can safely use it by supplying shoeIndexes which contains only the indexes you want to present and then iterate over them and create a respective <p> for each.
shoesData.types.color[1] won't work, you only have 1 element, so your index must be 0:
shoesData.types.color[0]

Javascript - Return json from fetch in an Object

I'm trying to make an application to get the recipes from https://edamam.com and I'm using fetch and Request object.
I need to make 3 request, and i thought that most beautiful way for do it is make an Object and a method that return the data in JSON.
I declarated into constructor a variable called this.dataJson, and i want to save there the data in JSON from the response. For that purpose i use this.
The problem is that i have a undefined variable.
.then( data => {this.dataJson=data;
console.log(data)} )
This is all my code.
class Recipe{
constructor(url){
this.url=url;
this.dataJson;
this.response;
}
getJson(){
var obj;
fetch(new Request(this.url,{method: 'GET'}))
.then( response => response.json())
.then( data => {this.dataJson=data;
console.log(data)} )
.catch( e => console.error( 'Something went wrong' ) );
}
getData(){
console.log("NO UNDFEIND"+this.dataJson);
}
}
const pa= new Recipe('https://api.edamam.com/search?...');
pa.getJson();
pa.getData();
I'm new studying OOP in JS and more new in Fetch requests...
If you guys can help me... Thanks very much!
Here's a solution using async-await (and a placeholder API):
class Recipe {
constructor(url) {
this.url = url;
this.dataJson;
this.response;
}
// the async keyword ensures that this function returns
// a Promise object -> we can use .then() later (1)
async getJson() {
try {
const response = await fetch(new Request(this.url, {
method: 'GET'
}))
const json = await response.json()
this.dataJson = json
} catch (e) {
console.error('Something went wrong', e)
}
}
getData() {
console.log("NO UNDFEIND:", this.dataJson);
}
}
const pa = new Recipe('https://jsonplaceholder.typicode.com/todos/1');
// 1 - here we can use the "then", as pa.getJson() returns
// a Promise object
pa.getJson()
.then(() => {
pa.getData()
});
If we want to stay closer to your code, then:
class Recipe {
constructor(url) {
this.url = url;
this.dataJson;
this.response;
}
getJson() {
// var obj; // not needed
// the "fetch" always returns a Promise object
return fetch(new Request(this.url, { // return the fetch!
method: 'GET'
}))
.then(response => response.json())
.then(data => {
this.dataJson = data;
// console.log(data) // not needed
})
.catch(e => console.error('Something went wrong'));
}
getData() {
console.log("NO UNDFEIND:", this.dataJson); // different syntax here
}
}
const pa = new Recipe('https://jsonplaceholder.typicode.com/todos/1');
// using "then", because the "fetch" returned a Promise object
pa.getJson()
.then(() => {
pa.getData();
});
The problem with your original code is that you initiate the request (pa.getJson()) and then immediately (on the next line) you want to read the data (pa.getData()). pa.getData() is called synchronously (so it happens in milliseconds), but the request is asynchronous - the data needs time to arrive (probably hundreds of milliseconds) - so, it's not there when you try to read it (it simply hasn't arrived yet).
To avoid this you have to use a technique to handle this asynchronous nature of the request:
use a callback function (blee - so last decade)
use a Promise object with then() (much better) or async-await (yeee!)
and call the pa.getData() when the response has arrived (inside the callback function, in the then() or after awaiting the result).

Pulling Data from JSON with React-Native

What's wrong with this picture ? :-)
I'm trying to pull values from my wordpress JSON objects.
I must not be addressing them the correct/proper way with React-Native.
Can someone direct me as to how to form the correct console log statement ?
As it stands right now, the variable 'theMediaLink' is coming up 'undefined' in the console log. :-(
state={
data:[]
}
fetchData = async() => {
const response = await
//response
fetch('http://example.com/wp-json/wp/v2/posts/')
//posts
const posts = await response.json();
this.setState({data:posts});
const theMediaLink = `https://example.com/wp-json/wp/v2/media/` + `${this.state.data.featuredmedia}`;
console.log('theMediaLink_value: ', theMediaLink);
}
I should add that the fetch is retrieving data as I use it later on with a FLATLIST to pull the posts. My question is I must be misforming the call, but how ?
This is more an issue of understanding of React rather than React Native.
Try this:
fetchData = async () => {
const URL = 'http://example.com/wp-json/wp/v2/posts/'
const response = await fetch(URL)
const posts = await response.json();
return this.setState({ data : posts }, () => {
const { data } = this.state
const theMediaLink = `https://example.com/wp-json/wp/v2/media/${ data.featuredmedia }`;
console.log('theMediaLink_value: ', theMediaLink);
});
}
Since setState is asynchronous, you won't be able to see the state update right away, that's why the callback is for.
More info on how to setState asynchronously and use its value after right here

Node.JS: How to scrape a json page for specific data

I would like to scrape this page: calendar events
for specific data, like formattedDate and description. How do I go about that in a module in Node.JS. I am having a hard time understanding the process in Node.JS.
Any help would go a long way, thanks in advance.
it's pretty simple, you can import the request module and use it. For example, see code below.
const request = require("request");
request("MY_URL", (error, response, body) => {
console.log('body:', body);
});
Also, you can try this here, on Repl.it
First of all, you need to parse your JSON, this allows you to access fields from received json.
const data = JSON.parse(body);
Now, if you want to access some information about an event you need to loop events and access what you need, something like:
const events = data.bwEventList.events;
events.map((data, index) => console.log(data.calendar))
Final code also on Repl.it
from nodeJS docs here
const http = require('http');
http.get('http://umd.bwcs-hosting.com/feeder/main/eventsFeed.do?f=y&sort=dtstart.utc:asc&fexpr=(categories.href!=%22/public/.bedework/categories/sys/Ongoing%22%20and%20categories.href!=%22/public/.bedework/categories/Campus%20Bulletin%20Board%22)%20and%20(entity_type=%22event%22%7Centity_type=%22todo%22)&skinName=list-json&count=30', (res) => {
const { statusCode } = res;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error('Request Failed.\n' +
`Status Code: ${statusCode}`);
}
if (error) {
console.error(error.message);
// consume response data to free up memory
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parsedData = JSON.parse(rawData);
console.log(parsedData["bwEventList"]["resultSize"]);
} catch (e) {
console.error(e.message);
}
});
}).on('error', (e) => {
console.error(`Got error: ${e.message}`);
});
see console.log(parsedData["bwEventList"]["resultSize"]);
slice parsedData as an array until you get what you want