Looping over an object that is within a another object - html

So I was working on this name card generator app. https://jsonplaceholder.typicode.com/users is the source of my database.
Any idea how to loop through the address part? My code so far.
import React, {useState, useEffect} from 'react';
import Namecard from './namecard'
function App() {
const [identis, setIdenti]=useState([]);
useEffect(()=>{
getIdenti()
},[]
);
const getIdenti = async()=>{
const acquired = await fetch(`https://jsonplaceholder.typicode.com/users`)
const data = await acquired.json()
setIdenti(data)
}
return (
<div>
{identis.map(identi=>(
<Namecard
name={identi.name}
email={identi.email}
address={identi.address}
/>
))}
</div>
)}
export default App

I think maybe you're going for something along these lines. Just to at least answer the question - here is how you would loop through the address. And I'm guessing you're trying to build up a readable string or something...
var users = [
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
}
}
];
var addressStr = '';
for (var user of users) {
addressStr = '';
for (var key of Object.keys(user.address)) {
key !== 'geo' && (addressStr += user.address[key] + ' ');
}
console.log(addressStr);
}

instead of looping through address part, just build a separate Address component.
const Address = ({ street, suite, ... }) => <h1>Street: {street}</h1>
const Namecard = ({ name, ..., children }) => <div> Name: {name} <div>{children}</div></div> // where children is the Address component
<Namecard
name={identi.name}
email={identi.email}
>
<Address {...identi.address} />
</Namecard>

Related

Avoid looping multiple times the same array in React and JSX

Suppose I have this array of objects:
const itensArray = [
{ "year": 2000, "text": "Lorem ipsum" },
{ "year": 2010, "text": "Hello World" },
{ "year": 2020, "text": "This is the end" }
];
Suppose it will be used to create elements in an timeline HTML structure, where the elements are separeted:
<div className="timeline-years">
<ul>{ yearsList }</ul>
</div>
<div className="timeline-texts">
<ul>{ textList }</ul>
</div>
I know one way to achieve this is to loop the same array two times:
const yearsList = itensArray.map(item =>
<li>{ item.year }</li>
);
const textList = itensArray.map(item =>
<li>{ item.text }</li>
);
How can I achieve the same result in one map only and using React and JSX?
The code below is wrong, but it illustrates what I want:
itensArray.map(item =>
let yearsList = <li>{ item.year }</li>
let textList = <li>{ item.text }</li>
);
Thanks!
If your target is to achieve this using only one loop then it could be a solution.
export default function App() {
const itensArray = [
{ "year": 2000, "text": "Lorem ipsum" },
{ "year": 2010, "text": "Hello World" },
{ "year": 2020, "text": "This is the end" }
];
const yearsList = []
const textList = []
itensArray.forEach((item)=>{
yearsList.push(<li>{ item.year }</li>)
textList.push(<li>{ item.text }</li>)
})
console.log(yearsList)
return (
<div className="App">
<ul>{yearsList}</ul>
<ul>{textList}</ul>
</div>
);
}
Dont afraid loop twice over one array, because data you should display in different places. You may preloop your array and assign your bunch of li elements as a const and put them in react fragments:
import React from 'react';
const itensArray = [
{ year: 2000, text: 'Lorem ipsum' },
{ year: 2010, text: 'Hello World' },
{ year: 2020, text: 'This is the end' },
];
function Component() {
const yearsList = (
<>
{itensArray.map((item) => (
<li>{item.year}</li>
))}
</>
);
const textList = (
<>
{itensArray.map((item) => (
<li>{item.text}</li>
))}
</>
);
return (
<>
<div className="timeline-years">
<ul>{yearsList}</ul>
</div>
<div className="timeline-texts">
<ul>{textList}</ul>
</div>
</>
);
}
export default Component;

React JSON is undefined

I'm fetching this JSON from an API:
{
"data": {
"email": "test#tre.com",
"inserted_at": "2021-03-30T15:37:06",
"links": [
{
"id": 1,
"title": "My link title",
"url": "http://google.com"
},
{
"id": 2,
"title": "My Youube title",
"url": "http://youtube.com"
}
]
}
}
I'm fetching it this way using Hooks:
export default function Notes() {
const [json, setJSON] = useState([]);
useEffect(() => {
fetch("http://localhost:4000/api/users/1", {
method: "GET"
})
.then((response) => response.json())
.then((json) => {
// console.log(data);
setJSON(json);
})
.catch((err) => {
console.error(err);
});
}, [setJSON]);
Then I try to show it like this:
return (
<>
<div className="content">
{JSON.stringify(json)}
<h1>{json.email}</h1>
</div>
</>
);
The line {JSON.stringify(json)} shows the JSON.
But the line <h1>{json.email}</h1> doesn't show anything.
I don't know why that happens and how can I access my variables.
Thanks . I appreciate any help
Is the data in the form of an array or an object?
You defined the initial state as and array ad hence you cannot do
// you can't do json.email if you expect the response as and array
const [json, setJSON] = useState([]);
change it to
const [json, setJSON] = useState({});
if it is an object. Then in the template do
{json.data && <h1>{json.data.email}</h1>}
<h1>{json.data && json.data.email}</h1>
instead of
<h1>{json.email}</h1>

Cant access key values from an Object in Reactjs after fetching

I have a user details page in Reactjs where I'm fetching the user details and populating it to the corresponding fields. But I'm not able to access key values from the user object.
My sample code is
function EditProfile(props) {
const [user, setUser] = useState()
useEffect(() => {
const fetchUserInfo = async () => {
const profileConfig = {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + auth.token
}
};
fetch(`http://localhost:4000/api/v1/user/me`, profileConfig)
.then(response => response.json())
.then(response => {
console.log("response: ", response.user);
if (response.success === true) {
setUser(response.user)
} else {
alert(response.message)
}
},
(error) => {
alert('User fetching faied: ' + error)
})
}
fetchUserInfo()
}, [])
return (
<div>{user.name}</div>
)
}
The response from the server (user object is)
{
"status": true,
"_id": "5ecfdc403165f709b49a4a0e",
"name": "Anand OL",
"gender": "male",
"dob": "2020-12-13T00:00:00.000Z",
"email": "anand#gmail.com",
"phone": "1234567890",
"createdAt": "2020-05-28T15:44:00.700Z",
"updatedAt": "2020-06-01T08:38:37.902Z",
"__v": 136,
"image": "5ecfdc403165f709b49a4a0e_Image.png"
}
when I try to access name from the user object like user.name
I'm getting an error user is not defined
You need to provide some initial state to display (or conditionally render) while the fetch is occuring.
const [user, setUser] = useState(); // <-- user is undefined!!
Conditionally render UI
return <div>{user && user.name}</div>;
or
return user ? <div>{user.name}</div> : null;
Note: Use caution with the former as not all falsey values are created equal, i.e. Consider return <div>{value && value.property}</div>, if/when value = 0 a falsey value, then a "0" will actually be rendered.
Or you can provide some default state
const [user, setUser] = useState({ name: '' });

Parse JSON in NodeJS

I am trying to fetch a JSON from a remote API using a simple NodeJS HTTP server (it uses request to make HTTP calls). When I run the HTTP response through some JSON validator, it says it's a valid JSON, but I'm not able to manage accessing keys or even keys which are arrays etc.
JSON looks like:
{
"submissions": [{
"token": "db7fa11f970f376cc17c5f8d1760ab98",
"created_at": "2017-03-02T13:01:35Z",
"saved_at": "2017-03-02T12:50:35Z",
"changed_at": "2017-03-02T12:50:35Z",
"email": "",
"data": {
"CompName": "",
"Name": "TestFirma01",
"MA_Name": "Robert Dotzlaff",
"CASFunction": "TestFunktion01",
"CreateDate": "02.03.2017",
"Street1": "TestStrasse",
"Zip1": "12345",
"Town1": "Berlin",
"PhoneFieldStr4": "07225919241",
"MailFieldStr1": "tes#mpl.de",
"Category1": [
"CRM"
],
"Category2": [
"mpl Finance"
],
"gwBranch": [
"B2B",
"B2C"
],
"ITDANZAHLMA": "<25",
"MPLUSERPOT": "<5",
"TurnOver": "<50.000",
"gwBranch_Product": "Maschinen",
"gwBranch_Solution": "Keine",
"Konkurenz": "Nein",
"MPLEINFUEHRUNG1": null,
"MPLEINFUEHRUNG2": [
"> 12 Monate"
],
"MPLEINFUEHRUNG3": "02.03.2017",
"MPLINFRASTRUKTUR1": [
"ERP"
],
"MPLINFRASTRUKTUR2": [
"Lotus"
],
"MPLINFRASTRUKTUR3": [
"RDP-Anbindung"
],
"MPLINTTHEMA1": [
"Projektmanagement",
"Vertrieb"
],
"MPLINTTHEMA2": [
"Auswertungen",
"Zeiterfassung"
],
"MPLINTTHEMA3": [
"Sonstiges"
],
"MPLSONSTIGEINFOS": "Es muss schnell sein",
"MPLKONKPRODUKT": "",
"ANSPR_TEAM": "Robert D",
"ANSPR_Entscheider": "Ptrick R",
"MPLENTSCHEIDUNG": "02.03.2017",
"ITDKLASSIFIZIERUNG": [
"sehr gut"
],
"NEXT_ACTION": [
"Testzugang"
]
},
"attachments": []
}]
}
NodeJS script as follows:
'use strict'
const Hapi = require('hapi');
const Express = require('express');
const Request = require('request');
const Vision = require('vision');
const Handlebars = require('handlebars');
const _ = require('lodash');
const LodashFilter = require('lodash.filter');
const LodashTake = require('lodash.take');
const JSONStream = require('JSONStream');
const jQuery = require('jsdom');
const server = new Hapi.Server();
server.connection({
host: '127.0.0.1',
port: 3000,
routes: {
cors: {
origin: ['*'],
additionalHeaders: ['X-API-KEY']
},
}
});
server.register(Vision, (err) => {
server.views({
engines: {
html: Handlebars
},
relativeTo: __dirname,
path: './views',
});
});
server.start((err) => {
if (err) {
throw err;
}
getJSON();
console.log(`Server running at: ${server.info.uri}`);
});
function getJSON() {
// URL and APIKEY ommitted for security reasons
var as_host = '';
var as_apiKey = ''
var as_endpoint = '/api/public/v1/projects/';
var as_projectId = '736';
var as_endpointExt = '/submissions';
var as_url = as_host + as_endpoint + as_projectId + as_endpointExt;
var options = {
url: as_url,
headers: {
'X-API-KEY': as_apiKey,
},
json: true
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
var jsonString1 = JSON.stringify(body);
var jsonObject = JSON.parse(jsonString1);
console.log("BODY2: " + jsonObject);
}
}
Request(options, callback);
}
The console.log("BODY2: " + jsonObject); outputs BODY2: [object Object] which is not what I want. When I remove json: true from the options variable for request, it outputs the JSON (or at least what looks like one), but I am still unable to access key / value pairs in the JSON. I need to access especially the data part of the JSON which contains the relevant data sets that need to be handed over to a second remote REST API (accepts only a special format, which is why I may not simply hand the retrieved JSON over to the other API). I have already tried several solutions and read a lot of posts on here, none of them seems to work for me (JSON.parse(), JSONStream.parse(), _.get() etc). Any help is much appreciated!

Getting json object data with react

I am attempting to pull data out of json like this, which is imported as "values"
{
"content": {
"person": [
{
"name": "Test"
"age" : "24:
}
]
}
}
I am using .map like below but getting the error .default.map is not a function I believe it is because i have objects not arrays, i've tried a bunch of stuff including object.keys but i'm getting errors all over the place, any direction would be appreciated.
import values from './sample.json'
const vals = values.map((myval, index) => {
const items = person.items.map((item, i) => {
return (
<div>{item.name}</div>
)
})
return (
<div>{items}</div>
)
})
I think your data and code have some errors. But after fixing those and also changing the name from 'person' to 'people' if that's what you are after, here's the code that does what you are trying to do:
var data = {
content: {
people: [
{
name: "Test",
age: 24,
},
{
name: "Foo",
age: 25,
},
],
},
};
var App = React.createClass({
render: function () {
var people = data.content.people.map(function (person) {
return <div>{person.name}</div>;
});
return <div>{people}</div>;
},
});
ReactDOM.render(<App />, document.getElementById("app"));
And here's the JSBin for that: https://jsbin.com/coyalec/2/edit?html,js,output
Update: I'm updating the answer with more detailed example. It now deals with data more generically, like it doesn't assume what are the entries of 'contents' and such, but it knows that each type like 'people' or 'pets' are an array.
var data = {
content: {
people: [
{
name: "Test",
age: 24,
},
{
name: "Foo",
age: 25,
},
],
pets: [
{
name: "Sweety",
age: 3,
},
{
name: "Kitty",
age: 5,
},
],
},
};
var App = React.createClass({
render: function () {
// Get the keys in data.content. This will return ['people', 'pets']
var contentKeys = Object.keys(data.content);
// Now start iterating through these keys and use those keys to
// retrieve the underlying arrays and then extract the name field
var allNames = contentKeys.map((t) =>
data.content[t].map((e) => <div>{e.name}</div>)
);
return <div>{allNames}</div>;
},
});
ReactDOM.render(<App />, document.getElementById("app"));
And here's the latest JSBin: https://jsbin.com/coyalec/4/edit?html,js,output