Hi I'm making SPA react program
I have some question
I want to know how can I use this JSON data HackNews
const [storyIds, setStoryIds] = useState([]);
const list = [];
useEffect(() => {
Top_API().then((res) => {
this.res = res.data.slice(0, 3);
this.res.forEach((ele) => {
axios
.get("https://hacker-news.firebaseio.com/v0/item/" + ele + ".json")
.then((res) => {
list.push({
id: res.data.id,
title: res.data.title,
url: res.data.url,
user: res.data.by,
score: res.data.score
});
setStoryIds(list);
});
});
});
}, []);
this is my code i want to print this api data
I print JSON data like this
{JSON.stringify(storyIds[0])}
This code works well. However, from the storyIds[1] arrangement, it is not visible on the screen. I checked that it was output from the console.
And when I go to a different page,
If I output the contents of my code array, an error occurs that the array cannot be found when you return to the page.
ex)
{JSON.stringify(storyIds[0].title)}
If you write like the code above, an error occurs that the array is not defined.
I've been trying to solve this situation for three days now without a proper solution.
The code that you print on the screen is as follows.
<div className="n1">
<a href={JSON.stringify(storyIds[0])}>
{JSON.stringify(storyIds[0])}
</a>
<br />
by: {JSON.stringify(storyIds[0])}
</div>
<div className="n2">{JSON.stringify(storyIds[1])}</div>
<div className="n3">{JSON.stringify(storyIds[2])}</div>
</div>
the data look's like
[{"id":30186326,"title":"Facebook loses users for the first time","url":"https://www.washingtonpost.com/technology/2022/02/02/facebook-earnings-meta/","user":"prostoalex","score":994},{"id":30186894,"title":"In second largest DeFi hack, Blockchain Bridge loses $320M Ether","url":"https://blockworks.co/in-second-largest-defi-hack-ever-blockchain-bridge-loses-320m-ether/","user":"CharlesW","score":400}]
how can I print this API response my screen?
You need to use async await with Promise.all for waiting for response from API
useEffect(() => {
Top_API().then(async (res) => {
this.res = res.data.slice(0, 5);
Promise.all(
this.res.map(async (r) => {
return await axios.get(
"https://hacker-news.firebaseio.com/v0/item/" + r + ".json"
);
})
).then((resolved) => {
resolved.map((resolve) => {
list.push({
id: resolve.data.id,
title: resolve.data.title,
url: resolve.data.url,
user: resolve.data.by,
score: resolve.data.score
});
});
setStoryIds(list);
});
});
}, []);
Related
So I'm getting incidents reports from Google Cloud API and displaying it. I'm trying to only display the ones that are happening on the US.
As you can see, the raw data from the API is like this:
I want to filter it, so I only get the ones that have us on it, how can I do it? This is the code now:
export const getGoogleStatus = async () => {
const response = await axios.get('https://status.cloud.google.com/incidents.json')
console.log('Raw Data: ', response.data)
const status = response.data.map((e) => {
return {
name: e.affected_products.map((e) => {
return e.title
}),
status: e.most_recent_update.status,
location: e.most_recent_update.affected_locations.map((e) => {
return e.title
}),
}
})
return status
}
You can use filter method in order to filter elements that doesn't match a specific criteria. Since you want only the items that are in the US, therefore you can check if it includes its code using include, which I believe it will be (us- as a substring.
export const getGoogleStatus = async () => {
const response = await axios.get('https://status.cloud.google.com/incidents.json')
console.log('Raw Data: ', response.data)
const status = response.data.map((e) => {
return {
name: e.affected_products.map((e) => {
return e.title
}),
status: e.most_recent_update.status,
location: e.most_recent_update.affected_locations.map((e) => {
return e.title
}).filter((e)=>e.includes('(us-')), //filters all elements that doesn't include '(us-' as a substring
}
})
return status
}
That seems like a static JSON file so you can use filter() to check if the location contains (us- as shown below:
location: e.most_recent_update.affected_locations.map((e) => {
return e.title
}).filter((r) => r.includes("(us-"))
If you want affected_products in US, then you can use the same filter on e.affected_products itself and check if affected_locations has any location from US.
my problem is about nested axios request. The code is very simple, with first axios.get i am fetching first portion of data and then using the given respons I am trying to fetch data from second endpoint. (code below)
const getData = async () => {
let returnSecoundValue = {}
try {
const response = await axios.get("http://127.0.0.1:8000/firstEndpoint/", {
auth: {
username: "x",
password: "y",
},
});
// console.log(response.data) <--- WORKS;
response.data.forEach(async element => {
const secoundData = await axios.get(`http://127.0.0.1:8000/secoundEndpoint/${element.id}/`, {
auth: {
username: "x",
password: "y",
},
});
returnSecoundValue[secoundData.data.id] = secoundData.data
});
console.log(returnSecoundValue) <--- WORKS;
setMyState({firstEnd: response.data, secoundEnd: empoRet})
} catch (err) {
console.error(err);
}
As in example above when I am finished fetching second data, I save it in my state as an object. The First element of an object is an array of objects, and the second is the object (used as disc).
Up to this point everything is fine, when I try and console.log it, it shows perfectly as I wanted. Problem starts when I'am trying to get the exact data from the second element.
With my fetched data I'am trying to do something like that:
myState.firstEnd.map((element) => {
try{
console.log(myState); (Works - log all values)
console.log(myState.secoundEnd); (Works - log all values of secoundEnd)
console.log(myState.secoundEnd[2]); (Return undefind)
<Component
key={element.id}
isActive={element.active}
title={element.title}
I have tried to do that in few approaches but each time I ended up with the same result. Is there a problem with mounting or is it something else?
Thanks to the comments, I figured out the problem.
This is the solution:
const secoundValue = response.data.map(async element => {
await axios.get(`http://127.0.0.1:8000/secoundEndpoint/${element.id}/`,
{
auth: {
username: "x",
password: "y",
},
});
});
Promise.all(secoundValue).then((res) => {
res.map((e)=>{
secoundEnd[e.data.id] = e.data
})
setMyState({ ads: resp.data, emp: empoRet });
});
I want to parse an external JSON file into my react app.
Here, I created a working example of what I want in Codesandbox.io:
https://codesandbox.io/s/morning-tdd-we2v3?file=/src/App.js
In this example, I am using some JSON data inside of the application but wanted to parse this data from an outside source file here: https://raw.githubusercontent.com/Forschung/AmbeentData/main/modems.json
I tried some ways but could be successful.
Best
Your JSON data format is invalid and that the reason for this problem.
you can fetch data as pure text and then fix them locally like this.
demo
const [data, setData] = useState([]);
useEffect(() => {
async function getData() {
fetch(
"https://raw.githubusercontent.com/Forschung/AmbeentData/main/modems.json"
)
.then(function (response) {
return response.text();
})
.then(function (txt) {
let d = txt.replace(/Brand/g, `"Brand"`);
d = d.replace(/Model/g, `"Model"`);
d = JSON.parse(d);
setData(d);
});
}
getData();
}, []);
'json file is wrong' the correct one should be
"key": "value"
You did this as
key: "value"
Wrong Json file
[
{ Brand:"Actiontec", Model:"GT784WNV" },
{ Brand:"Actiontec", Model:"MI424WR" },
{ Brand:"AirTies", Model:"Air 4450" }
]
Must Have Json File
[
{
"Brand":"Actiontec",
"Model":"GT784WNV"
},
{
"Brand":"Actiontec",
"Model":"MI424WR"
},
{
"Brand":"AirTies",
"Model":"Air 4450"
}
]
The answer to the second question is that you can make this request very simply using the axios library. I'll leave the sample code and the live example.
Proje Test Link
Sample code
useEffect(() => {
axios(
"json link"
)
.then((res) => setDatas(res.data))
.catch((e) => console.log(e))
.finally(() => console.log('finally'));
}, []);
In Javascript I have to print in the document a JSON with some data from MySQL database and I want to remove the break lines but I cannot achieve it.
I get the data through node.js and I use express.js for printing it on a web browser.
This is the result:
As you can see, there is a break line between both rows and I want to remove it since it is causing issues when I try to read the JSON on the android application I am building.
I have tried to search on internet about how to achieve it, most answers were about using str.replace(/\r?\n|\r/g, '') but it did not work in my case.
This is the JS code I currently have:
var dbData = '<%-usersList%>';
dbData = JSON.parse(dbData.replace(/\r?\n|\r/g, ''));
document.write(JSON.stringify(dbData));
And this is how I pass the data from node.js:
app.get('/dbJSON', function (req, res) {
getDBData().then((data) => {
res.render('./dbJSON.ejs', {
usersList: JSON.stringify(data.usersList)
});
});
});
This function calls the js file that gets the data from the db:
function getDBData() {
const users = new Promise((resolve, reject) => {
dbConnection
.getUsers()
.then(data => {
resolve(data)
})
});
const groups = new Promise((resolve, reject) => {
dbConnection
.getGroups()
.then(data => {
resolve(data)
})
});
const frmTexts = new Promise((resolve, reject) => {
dbConnection
.getFrmTexts()
.then(data => {
resolve(data)
})
});
return Promise.all([users, groups, frmTexts])
.then(data => {
return {
usersList: data[0],
groupsList: data[1],
frmTextsList: data[2]
}
});
}
Result of printing out data.usersList (in node.js):
Edit: Fixed! The reason of why I wanted to delete the break lines was because I had issues with parsing the JSON on Android Studio but I have just figured out it was due to I did not add the http:/ in the url string (my bad). Now my android app is working.
#Adrian2895,
Simply convert it to string and this will remove new-line/carriage-return. And also the above code is working fine (which I referred to use deep-cloning to remove any attribute).
You can use the concept of deep cloning to get rid of unwanted attributes from JSON obj.
var rawData = [{
'iduser':1,
'user':'XXX',
'password': 'XXX123',
'groups_idgroup': 1,
'idgroup':1,
'name': 'James'
},
{
'iduser':9,
'user':'XXX',
'password': 'XXX123',
'groups_idgroup': 2,
'idgroup':2,
'name': 'James'
}];
rawData.forEach( function(item, index){
rawData[index] = Object.assign({}, item, {'user':undefined, 'password':undefined, 'name': undefined} );
console.log(JSON.stringify(rawData));
Output:-
[{"iduser":1,"groups_idgroup":1,"idgroup":1},{"iduser":9,"groups_idgroup":2,"idgroup":2}]
I'm using koa v2 with pg-promise. I try to do a simple SELECT 2 + 2; within a Parameterized/Prepared Statement to test my setup:
// http://127.0.0.1:3000/sql/2
router.get('/sql/:id', async (ctx) => {
await db.any({
name: 'addition',
text: 'SELECT 2 + 2;',
})
.then((data) => {
console.log('DATA:', data);
ctx.state = { title: data }; // => I want to return num 4 instead of [Object Object]
})
.catch((error) => {
console.log('ERROR:', error);
ctx.body = '::DATABASE CONNECTION ERROR::';
})
.finally(pgp.end);
await ctx.render('index');
});
Which is rendering [Object Object] in the templates and returning this to the console from pg-monitor:
17:30:54 connect(postgres#postgres)
17:30:54 name="addition", text="SELECT 2 + 2;"
17:30:54 disconnect(postgres#postgres)
DATA: [ anonymous { '?column?': 4 } ]
My problem:
I want to store result 4 in ctx.state. I don't know how can I access it within [ anonymous { '?column?': 4 } ]?
Thank You for your help!
Edit:
I found another recommended(1) ways(2) to dealing with named parameters in the official wiki.
// http://127.0.0.1:3000/sql/2
router.get('/sql/:id', async (ctx) => {
const obj = {
id: parseInt(ctx.params.id, 10),
};
await db.result('SELECT ${id} + ${id}', obj)
.then((data) => {
console.log('DATA:', data.rows[0]['?column?']);
ctx.state = { title: data.rows[0]['?column?'] }; // => 4
})
.catch((error) => {
console.log('ERROR:', error);
ctx.body = '::DATABASE CONNECTION ERROR::';
})
.finally(pgp.end);
await ctx.render('index');
});
I changed the any object to result, which returning the raw text. Than I access number 4 like a javascript object. Am I doing something wrong? Is there another way to access this value?
What is the recommended, more faster, safer way of usage?
Since you are requesting just one value, you should use method one:
const {value} = await db.one({
name: 'addition',
text: 'SELECT 2 + 2 as value',
}); // value = 4
And for such example you cannot use types PreparedStatement or ParameterizedQuery, because they format query on the server side, and PostgreSQL does not support syntax like $1 + $1.
The real question is - do you really need those types?