How to use map on json response returned by a REST API with ReactJs - json

I've a json. The only thing I want is title from the json.
{
"projects": [
{
"id": 1,
"title": "Bike Servicing System",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 2,
"title": "Air Traffic Controller",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 3,
"title": "Program Counter",
"language": "JavaFX",
"requires": "JDK 8"
}
],
"profile": {
"name": "typicode"
}
}
I am using fetch and componentDidMount. I want to do it musing map method to iterate through. Though I don't need <ul> and <li> tags really. I will remove them later. My React code is
import React, { Component } from "react";
class ProjectStack extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false
};
}
componentDidMount() {
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json.projects
});
});
}
render() {
var { isLoaded, items } = this.state;
var i=0;
if (!isLoaded) return <div>Loading...</div>;
return (
<div>
<ul>
{
items.map(item => (
<li key={item[i++].id}>
Projects: {item[i++].title}
</li>
))
}
</ul>
</div>
);
}
}
export default ProjectStack;
Apparently, there is something that I don't know because I am getting this error.
PS: This question is different from mine

The JSON of the URL you are fetching is this:
[
{
"id": 1,
"title": "Bike Servicing System",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 2,
"title": "Air Traffic Controller",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 3,
"title": "Program Counter",
"language": "JavaFX",
"requires": "JDK 8"
},
{
"id": 4,
"title": "Dove Tail",
"language": "JavaFX",
"requires": "JDK 8"
}
]
So for correctly set the data in the state you need to:
componentDidMount() {
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json
});
});
}
Besides correcting the error they have already told you related the map loop.

I found 2 mistakes from your code.
The first one is you didn't check the response data.
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
.then(res => res.json())
.then(json => {
console.log(json); // it is an Array not object.
this.setState({
isLoaded: true,
items: json
});
});
And the second is you didn't use the map() properly.
/*{
items.map(item => (
<li key={item[i++].id}>
Projects: {item[i++].title}
</li>
))
}*/
// items has objects, so you should use map() like this.
{
items.map(item => (
<li key={item.id}>
Projects: {item.title}
</li>
))
}
The below code is one way to achieve what you want.
class ProjectStack extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false
};
}
componentDidMount() {
fetch("http://my-json-server.typicode.com/tmtanzeel/json-server/projects/")
.then(res => res.json())
.then(json => {
console.log(json);
this.setState({
isLoaded: true,
items: json
});
});
}
render() {
const {
isLoaded,
items
} = this.state;
console.log(items);
if (!isLoaded) return ( < div > Loading... < /div>);
return ( <
div >
<
ul > {
items.map(item => ( <
li key = {
item.id
} > Projects: {
item.title
} < /li>
))
} <
/ul> <
/div>
);
}
}
ReactDOM.render( <
ProjectStack / > , document.getElementById('root')
)
<script crossorigin src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<div id="root"></div>

Related

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

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

react native how to filter data with some key object on json

if I have json like this
-----------------
{
title: "The Basics - Networking",
description: "Your app fetched this from a remote endpoint!",
movies: [
{
title: "Star Wars",
category: "space",
releaseYear: "1977"
},
{
title: "Back to the Future",
category: "time"
releaseYear: "1985"
},
{
title: "The Matrix",
category: "scifi",
releaseYear: "1999"
},
{
title: "Inception",
category: "fantasy",
releaseYear: "2010"
},
{
title: "Interstellar",
category: "space"
releaseYear: "2014"
}
]
}
-----------------
I need to filter some data of category = space
but I don't know how to filter data after fetch json form webservice
I want only data form category = space
(It's mean I want to get interstellar and star wars)
and set to datasource
like a " dataSource: ds.cloneWithRows(responseJson.movies)" but this method get all row without filter
componentDidMount() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: ds.cloneWithRows(responseJson.movies),
}, function() {
// do something with new state
});
})
.catch((error) => {
console.error(error);
});
}
Use Array#Filter like this:
const movies = [{
title: "Star Wars",
category: "space",
releaseYear: "1977",
},
{
title: "Back to the Future",
category: "time",
releaseYear: "1985",
},
{
title: "The Matrix",
category: "scifi",
releaseYear: "1999",
},
{
title: "Inception",
category: "fantasy",
releaseYear: "2010",
},
{
title: "Interstellar",
category: "space",
releaseYear: "2014",
}
];
const space = movies.filter(x => x.category === 'space');
console.log(space);
Here you are another Array#Filter example,
filter posts where userId is 1.
https://jsonplaceholder.typicode.com/posts :
class Data extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
return fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
this.setState({ data: data.filter(d => d.userId === 1) })
})
.catch(error => {
console.error(error);
});
}
render() {
return (
<div>
<h1>Posts JSON:</h1>
<pre>
{JSON.stringify(this.state.data, null, 2)}
</pre>
</div>
);
}
}
ReactDOM.render(
<Data />,
document.getElementById('container')
);
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Import JSON data in to array in REACTJS

So ive been looking at this for a couple hours now trying to get my head around it but I just cant figure it out.
I have a json file located at '/src/data/topbar.json' which i want to include in my topbar-container component which will be used to generate the top menu.
What am I doing wrong here?
topbar.json:
{
"topbarLinks": [
{
"id": 1,
"icon": "header__topbar__list__link__icon glyphicon glyphicon-home",
"text": "home",
"link": "/"
},
{
"id": 2,
"icon": "header__topbar__list__link__icon glyphicon glyphicon-euro",
"text": "Pricing",
"link": "/pricing"
},
{
"id": 3,
"icon": "header__topbar__list__link__icon glyphicon glyphicon-exclamation-sign",
"text": "Help",
"link": "/help"
},
{
"id": 4,
"icon": "header__topbar__list__link__icon glyphicon glyphicon-question-sign",
"text": "FAQ",
"link": "/faq"
},
{
"id": 5,
"icon": "header__topbar__list__link__icon glyphicon glyphicon-edit",
"text": "Register",
"link": "/register"
},
{
"id": 6,
"icon": "header__topbar__list__link__icon glyphicon glyphicon-share",
"text": "Login",
"link": "/login"
}
]
}
topbar-container.js
import React, { Component } from 'react';
import './topbar-container.scss';
import Link from '../topbar-link/topbar-link';
require ('../../data/topbar.json');
class TopbarContainer extends Component {
constructor() {
super();
this.State = {
topbarLinks: []
}
}
componentDidMount() {
fetch('../../data/topbar.json')
.then(results => {
return results.json();
}).then(data => {
let topbarLinks = data.results.map((topbarLinks, key) => {
return (
<Link
key={topbarLinks.id}
text={topbarLinks.text}
icon={topbarLinks.icon}
link={topbarLinks.link}
/>
)
})
})
}
render() {
return (
<div className="container-fluid header__topbar">
<div className="row">
<div className="container">
<ul className="header__topbar__list">
{this.state.topbarLinks}
</ul>
</div>
</div>
</div>
);
}
}
export default TopbarContainer;
You can't fetch a local JSON file, you either have to import it, or setup a webserver that will serve that JSON file
import myJson from '../../data/topbar.json';
Then just map over it and don't forget to setState
componentDidMount() {
let topbarLinks = myJson.topbarLinks.map((topbarLinks, key) => {
return (
<Link
key={topbarLinks.id}
text={topbarLinks.text}
icon={topbarLinks.icon}
link={topbarLinks.link}
/>
)
})
this.setState({topbarLinks: topbarLinks}); // <--
//or just this.setState({ topbarLinks });
}
and as somebody else noted this.state has to be lowercase
topbar.json:
export default {
"topbarLinks": []
}
then you can simply import it without fetch
import data from '../../data/topbar.json'
let topbarLinks = data.results.map((topbarLinks, key) => {
return (
;
I don't think that State should be capitalized in this.State in your constructor.
Change map function to data.topbarLinks.map to access json data.
let topbarLinks = data.topbarLinks.map((topbarLinks, key) => {
return (
<Link
key={topbarLinks.id}
text={topbarLinks.text}
icon={topbarLinks.icon}
link={topbarLinks.link}
/>
)
})
And then set state
this.setState({topbarLinks: topbarLinks});
Change your initial state as this.State to this.state in constructor.