React JSON is undefined - json

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>

Related

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: '' });

In a JSON file I need to access to an attribute name with ':' in it

I'm a react-native noob.
I need to read a link inside a JSON field called 'wp:featuredmedia.href'.
obviusly i can't put the ':' char in the code.
I've tried in this way... but I've no success :(
componentDidMount(){
const { navigation } = this.props;
const id = navigation.getParam('id', );
//const percorso = 'responseJson.wp:featuredmedia.rendered';
return fetch('https://www.seisnet.it/wp-json/wp/v2/posts/'+id)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
title: String(responseJson.title.rendered),
photos: String(responseJson.wp:featuredmedia),
}, function(){});
})
.catch((error) =>{
console.error(error);
});
}
EDIT 1
this is a section of the json file:
// 20190726085445
// https://www.seisnet.it/wp-json/wp/v2/posts/1967
"_links": {
"self": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/posts/1967"
}
],
"collection": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/posts"
}
],
"about": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/types/post"
}
],
"wp:featuredmedia": [
{
"embeddable": true,
"href": "https://www.seisnet.it/wp-json/wp/v2/media/1971"
}
],
"wp:attachment": [
{
"href": "https://www.seisnet.it/wp-json/wp/v2/media?parent=1967"
}
],
}
}
the field i've to read contains a link to another json file.
i've tried: JSONResponse_embedded["wp:featuredmedia"] and JSONResponse["wp:featuredmedia"]. the first give me the error "undefined is not an object" while the second give me nothing in output
Instead of responseJson.wp:featuredmedia, try responseJson["wp:featuredmedia"]
JavaScript object: access variable property by name as string

Iterate a JSON array by a key value in react-native

Is there anyway to get a value in an object from a json array. I need to get a value from an object based on another value.
I have my code like:
export default class StandardComp extends Component {
constructor(props) {
super(props)
this.state = {
id: '',
email: 'abc#gmail.com',
dataSource: []
};
}
componentDidMount(){
fetch(someURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({dataSource: responseJson})
//dunno what to do here
})
.catch((error) => {
console.error(error);
})
}
}
My "responseJson" is something like this. Then providing the key value (abc#gmail.com), how could I get the string "abcdef"?
[
{
"id": "qwerty",
"email": "cat#gmail.com",
"name": "cat"
},
{
"id": "abcdef",
"email": "abc#gmail.com",
"name": "abc"
}
{
"id": "owowao",
"email": "dog#gmail.com",
"name": "dog"
},
]
Thank you in advance.
Find the element that matches email and return the id.
array::find
const data = [
{
"id": "qwerty",
"email": "cat#gmail.com",
"name": "cat"
},
{
"id": "abcdef",
"email": "abc#gmail.com",
"name": "abc"
},
{
"id": "owowao",
"email": "dog#gmail.com",
"name": "dog"
},
];
const findIdByEmail = (data, email) => {
const el = data.find(el => el.email === email); // Possibly returns `undefined`
return el && el.id; // so check result is truthy and extract `id`
}
console.log(findIdByEmail(data, 'cat#gmail.com'));
console.log(findIdByEmail(data, 'abc#gmail.com'));
console.log(findIdByEmail(data, 'gibberish'));
The code will depend on how you get the value abc#gmail.com.
You'll probably need to pass it in as an argument to componentDidMount via a prop? Or extract it to a separate function. It just depends.
Something like this is the most basic way I'd say.
const value = responseJson.filter(obj => obj.email === 'abc#gmail.com')[0].id
Here it is implemented in your class.
export default class StandardComp extends Component {
...
componentDidMount(){
fetch(someURL, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({ dataSource: responseJson })
const { email } = this.state
const value = responseJson.filter(obj => obj.email === email)[0].id
})
.catch((error) => {
console.error(error);
})
}
}

Angular HttpClient-subscribe select property from data

I'm really sure about, that this question is answered multiple times in here. But I can't find them/don't knwo which terms to search for.
I've got a JSON-file looking like that:
{
"pages": [{
"displayname": "PageA",
"url": "http://google.de",
"icon": "iconZ"
},
{
"displayname": "PageB",
"url": "http://www.pageb.co.uk",
"icon": "iconY"
}
],
"icons": [{
"alias": "iconZ",
"filename": "iconZ.svg"
},
{
"alias": "iconY",
"filename": "iconY.svg"
}
]
}
Now I'm using the HttpClient (here called httpService) to get the data from the file.
this.httpService.get('./assets/pageconfig.json').subscribe(
data => {
this.arrAdress = data as string[];
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
I want to use the content of pages in my ngFor in the Frontend and I want to get an array of the icon-content for use in the Backend. How can I select/split the data by using the properties.
Thanks for your help
Elias
Considering your pageconfig.json is used in both front and backend, and that you just need the "pages" attribute in your angular app, you may get it this way:
this.httpService.get('./assets/pageconfig.json').subscribe(
data => {
this.arrAdress = data.pages;
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
You don't need to cast the data type.
You could also use the rxjs observable map chaining to parse your data and get only what interests you:
import { map } from 'rxjs/operators';
this.httpService.get('./assets/pageconfig.json')
.pipe(map(data => data.pages))
.subscribe(pages=> {
this.arrAdress = pages;
}.catch((err: HttpErrorResponse) => {
console.log(err.message);
});
I hope this is what you were looking for.
Need to remove string[], instead use Array of object or any.
this.httpService.get('./assets/pageconfig.json').subscribe(
data => {
this.arrAdress = data;
},
(err: HttpErrorResponse) => {
console.log(err.message);
}
);
sendData(icon){
const matched = this.arrAdress.icons.filter(iconObj => iconObj.alias === icon);
console.log(matched);
}
**Template:**
<div *ngFor="let adress of arrAdress?.pages;" (click)="sendData(adress.icon)">
<span>{{adress.displayname}}</span>
</div>
You have two solutions here to solve this issue
Suppose httpClient.Delete() option returns back you an observable object with employeeId as property in it.
Solution 1 (example)
Create an local variable and assign data to it using let statement (e.g. let response: any = data;).
delete(employee: any) {
this.employeeService.deleteEmployee(employee.id)
.subscribe(
data => {
let response: any = data;
// now you can use response.employeeId
},
(error) => {
console.log(error)
},
() => {
console.log("The operation has been completed")
}
);
}
Solution 2 (example)
Assign type any (e.g. (data : any) to received response
delete(employee: any) {
this.employeeService.deleteEmployee(employee.id)
.subscribe(
(data: any) => {
// now you can use data.employeeId
},
(error) => {
console.log(error)
},
() => {
console.log("The operation has been completed")
}
);
}

How do I grab this API data using ReactJS

Hi Could anyone help with this? I am trying to grab my API data from this API request but cannot seem to manage how to grab the bit I need.
Basically what I need to display in my <p></p> is this "astronomical": "0.4838725338",
Here is my json data
{
"links": {
"next": "https=DEMO_KEY",
},
"element_count": 6,
"near_objects": {
"2018-12-28": [
{
"links": {
"self": "x"
},
"id": "2450238",
"estimated_diameter": {
"kilometers": {
"estimated": 0.6089126221,
"estimatedmax": 1.3615700154
}
},
"is_potentially": false,
"approach": [
{
"date": "2018-12-28",
"epoch": 1545984000000,
"distance": {
"astronomical": "0.4838725338",
"lunar": "188.2264099121",
},
"orbitinody": "Nobes"
}
],
And here is my Component
class App extends Component {
state = {
data : []
}
componentDidMount() {
this.fetchasa();
}
fetchasa = () => {
fetch('https:?de_KEY')
.then((response) => response.json())
.then((result) => this.setState({
data: result.near_objects.2018-12-28.approach.distance[0]
}))
}
render() {
const {data} = this.state;
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Edit <code>src/App.js</code> and save to reload.</p>
<p>astronomical: {data}</p>
</header>
</div>
);
}
}
export default App;
Please help and thank you in advance :D
Try with:
result.near_objects['2018-12-28'][0].approach[0].distance.astronomical
If you don't know the index names of near_objects prior to the request, you can get the date value like this
const [first] = Object.keys(result.near_objects)
result.near_objects[first][0].approach[0].distance.astronomical