Pulling Data from JSON with React-Native - json

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

Related

React LocalStorage issue not stored in localstorage

I am using Local Storage for my login page
but my variables not storing in the local storage I don't know why....
I am using the following code on my button click....
But the APi i am using is correct... It works fine
res.data.status gives true or false,Inside Axios .then => If is used for correct username and password and else is used for incorrct user
This is my Code:
async function handleSubmit(e) {
var url = 'http://localhost/project/login.php?name='+name+"&price="+price;
const formData = new FormData();
formData.append('avatar',"hi")
await axios.post(url, formData)
.then(res => {
if(!res.data.status){
localStorage.setItem('username', name);
alert(res.data.message);
}else{
alert(res.data.message);
}
})
}
if your variable is not stored in the localStorage. that's because of the condition you have. also as you're sure that your API is working fine and you can successfully make a request and receive a response. then the issue is with the condition. because from your code. you're making conditions only if the request is not successful. you don't have the condition for success.
async function handleSubmit(e) {
var url = 'http://localhost/project/login.php?name='+name+"&price="+price;
const formData = new FormData();
formData.append('avatar',"hi")
await axios.post(url, formData)
.then(res => {
if(!res.data.status){ <= remove the !
localStorage.setItem('username', name);
alert(res.data.message);
}else{
alert(res.data.message);
}
})
}

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)
}
}

How can I make multiple API calls with the same key

I'm working on my Project and currently I have one API call to spoonacular's search by recipe GET request. I want to add the search by video GET Request but I seem to having problems getting both to render at once into the DOM. How can I fix this issue?
const apikey = '';
const urls = { search:'https://api.spoonacular.com/recipes/complexSearch',
videos: 'https://api.spoonacular.com/food/videos/search'
};
function queryParams(params) {
const queryItems = Object.keys(params).map(key=>`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
return queryItems.join('&');
}
///render results
function getRecipe(tacos,maxResults){
const params ={
query: tacos,
number: maxResults,
};
const queryString = queryParams(params)
const url = urls+'?'+queryString +'&apiKey='+ apikey;
console.log(url);
fetch(url)
fetch(urls.search)
.then(response =>{
if(response.ok){
return response.json();
}
throw new Error(response.statusText);
})
.then(responseJson => displayResults(responseJson))
.catch(err =>{
$('#js-error-message').text(`Something went wrong: ${err.message}`);
});
}
Your urls is an object containing two strings. You need to treat it as such and make two separate calls.
You should have a fetch(urls.search) and fetch(urls.videos) call, each with their own response chain.
I'm not sure this code is doing what you think it is:
const url = urls+'?'+queryString +'&apiKey='+ apikey;
You'll need to append the queryString and apiKey to each string within urls separately. Something like
const searchUrl = urls.search+'?'+queryString +'&apiKey='+ apikey;
const videosUrl = urls.videos+'?'+queryString +'&apiKey='+ apikey;

ReactJS fetch data from custom API and render data

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()); }
}

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