I am trying to access variables from json in react component.
This is JSON I am getting:
{
"id": 5,
"title": "Hello",
"text": "Hello, this is my first article...",
"picture": "pic",
"comments": [],
"user": {
"id": 3,
"name": "Anonim",
"password": "123456"
}
}
The attached user is person who created the post.
The attached comments is list of comments related to this post.
In routing I am doing the following:
<Switch>
<Route path='/' exact component={PostsPage} />
<Route path='/:id' exact component={PostProfilePage} />
</Switch>
In react class component
class PostProfile extends Component {
constructor(props){
// Pass props to the parent component
super(props);
// Set initial state
this.state = {
// State needed
post: []
};
}
componentDidMount() {
this.fetchPost();
}
fetchPost() {
const {match} = this.props
const id = match.params.id
console.log(id)
fetch('/'+id)
.then(res => {
return res.json();
})
.then(data => {
this.setState({
post: data
});
})
.catch(err => {
console.log(err);
});
}
render() {
return (
<div>
<li> {this.state.post.title} </li>
<li> {this.state.post.text} </li>
</div>
)
}
}
export default withRouter(PostProfile)
does not work
<li> {this.state.post.user.name} </li>
<li> {this.state.post.comments...} </li>
Why I cannot access user and comments?
And is it possible to get user and comments in different components? (not calling the fetch method again and again)?
Thank you in advance!
Your post at first time has no data, so you need something like:
import React, { Component } from 'react';
export default class Test extends Component {
constructor(props) {
// Pass props to the parent component
super(props);
// Set initial state
this.state = {
// State needed
post: []
};
}
componentDidMount() {
this.fetchPost();
}
fetchPost() {
fetch('https://swapi.co/api/people/1')
.then(res => {
return res.json();
})
.then(data => {
this.setState({
post: data
});
})
.catch(err => {
console.log(err);
});
}
render() {
const show = this.state.post.length === 0 ?
<h1> ...loading </h1>
: <h1> {this.state.post.birth_year} </h1>
return (
<div>
<h1> { show } </h1>
</div>
)
}
}
Related
I have some code that allows the user to click a image to then update the page and display the clicked on champions name. the json data looks like this -http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion/Alistar.json
I console.log response.data and see a object of objects and am wondering how to get passed the section that has the response.data.(whatever champion the user picked). I have tried adding a variable like response.data.champion but I assume no variables can be passed like that seeing how it doesnt work.
Not sure if its even worth posting the code but just in case! My code is below, the fetch im trying to go through is in NewChamp function.
To make my request simpler, All i want to know for example is how i would get response.data.(whatever the user clicked).key from any possible champion clicked like http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion/Alistar.json or http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion/Anivia.json
or whatever other champion the user clicks.
import React, { Component } from 'react';
import './Champions.css';
class AllChamps extends Component {
render() {
let champion = this.props.champion;
return(
<div className='champions'>
<h1> all champions</h1>
{Object.keys(this.props.champions).map((s) => (
<div className='champs' onClick={() => this.props.NewChamp({s, champion})}>
<img
alt='Champion Images'
src={`http://ddragon.leagueoflegends.com/cdn/10.16.1/img/champion/${s}.png`}
onClick={this.props.onClick}
></img>
{s}
</div>
))}
</div>
)}}
class SpecificChamp extends Component {
render() {
let champion = this.props.champion
let Spec = champion[champion.length - 1];
return (
<div className='champions'>
<h1> 1 champions</h1>
<div className='champs'>
<button onClick={this.props.onClick}></button>
{Spec}
</div>
</div>
)}
}
class Champions extends Component {
constructor(props) {
super(props);
this.handleAllChamps = this.handleAllChamps.bind(this);
this.handleSpecificChamp = this.handleSpecificChamp.bind(this);
this.NewChamp = this.NewChamp.bind(this);
this.state = {
champions: [],
champion: [],
clickedChamp: false,
thisChamp: 'ahri'
}}
NewChamp = (props) =>
{
let s = props.s;
props.champion.push(s);
fetch(`http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion/${s}.json`)
.then(response => { return response.json() })
.then((response) => {
Object.keys(response.data).map((a) => (s = a
))})
fetch(`http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion/${s}.json`)
.then(response => { return response.json() })
.then((response) => {
console.log(s)
console.log(response.data)
console.log(props.champion)
})
console.log(`http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion/${s}.json`);
}
handleAllChamps = (props) => {
this.setState({ clickedChamp: true,
})};
handleSpecificChamp = () => {
this.setState({ clickedChamp: false,
})};
componentDidMount(props) {
const apiUrl = `http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion.json`;
fetch(apiUrl)
.then(response => { return response.json() })
.then((response) => {
this.setState({
champions: response.data
}, () => (this.state.champions))
return
})
}
render() {
const clickedChamp = this.state.clickedChamp;
let display;
if (clickedChamp ) {
display = <SpecificChamp champion={this.state.champion} onClick={this.handleSpecificChamp} s={this.state.thisChamp}/>;
} else {
display = <AllChamps champions={this.state.champions} onClick={this.handleAllChamps} NewChamp={this.NewChamp} thisChamp={this.state.thisChamp} champion={this.state.champion} />;
}
return (
<div>
<div className='champions'></div>
{display}
</div>
);
}
}
export default Champions;
Your response is in the form of Object of Objects. You've to use JSON.stringify(response.data) in order to view the entire data as a string in the debug console.
You will have to destructure the Object of objects.
Object.keys(response.data).map((key)=> console.log(response.data[key]))
In this case if it is just one key
response.data[s]
This is the api http://skunkworks.ignitesol.com:8000/books/ ,
I am trying to fetch the array results from it using the fetch method but instead get an error cannot fetch value of undefined
import React, { Component } from 'react';
class App extends Component {
constructor() {
super()
this.state = {
books: []
}
}
componentDidMount() {
fetch('http://skunkworks.ignitesol.com:8000/books/')
.then(res => res.json())
.then(data => this.setState({ books: data }))
.catch(e => {
console.log(e);
return e;
});
}
render() {
let book = []
book = this.state.books.results;
console.log(book[0])
return (
<div>
<h1>Books</h1>
</div>
)
}
}
export default App;
this is my code.
Also I have observed that json data are usually like [{}] but here it is {} format.
please suggest me some solution.....
As I see from your url link, you json array of data is present in the results key of the returned object from the API.
So if you're only interested by the results you should do something like that :
import React, { Component } from 'react';
class App extends Component {
state = {
books: []
}
async componentDidMount() {
const objectFromUrl = await fetch('http://skunkworks.ignitesol.com:8000/books/')
const data = await objectFromUrl.json() //first way
// or you can use destructuring way
const { results } = await objectFromUrl.json() //second way
this.setState({
books: data.results // results key contains your '[{}]' data an array of objects
})
}
render() {
const { books } = this.state
return (
<div>
<h1>Books</h1>
{books.map(book => (
<h2> {book.id} </h2>
)}
</div>
);
}
// You can use destructuring again to get only key you're interested by
render() {
const { books } = this.state
return (
<div>
<h1>Books</h1>
{books.map(({id, formats}) => (
<h2> {id} </h2>
<h2> { formats[ˋapplication/pdf’] } </h2>
)}
</div>
);
}
}
This is the first time I'm working with APIs using ReactJS. I know the basics of reactjs pretty well but I'm unable to read the response. I've a json response from youtube api.
Initially i got
TypeError: items.map is not a function.
But then i realized that i might be getting an Object and not an array. I solved the problem by items: json.statistics. But now I'm getting other error i.e
TypeError: items is undefined
I just want to fetch 3 information viz viewCount, subscriberCount and videoCount. I've written this code
import React, {Component} from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false
}
}
componentDidMount() {
fetch('https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCOYqNBjmWF8j-PzI7ZPjt_w&key=AIzaSyAMeZQW6sUQgLdDTnMVeokfbcFcT2A9SuA')
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json.statistics
})
});
}
render() {
var {isLoaded, items} = this.state;
if(!isLoaded) {
return (<div>Loading...</div>)
}
else {
return (
<div>
<ul>
{
items.map(item => (
<li key={item.id}>
Total views: {item.viewCount}
Total subscribers: {item.subscriberCount}
Total videos: {item.videoCount}
</li>
))}
</ul>
</div>
)
}
}
}
export default App;
It seems like the problem is in your setState(). Try something like this:
import React, { Component } from "react";
import "./styles.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
isLoaded: false
};
}
componentDidMount() {
fetch(
"https://www.googleapis.com/youtube/v3/channels?part=statistics&id=UCOYqNBjmWF8j-PzI7ZPjt_w&key=AIzaSyAMeZQW6sUQgLdDTnMVeokfbcFcT2A9SuA"
)
.then(res => res.json())
.then(({ items }) => {
this.setState({
isLoaded: true,
items
});
});
}
render() {
var { isLoaded, items } = this.state;
if (!isLoaded) return <div>Loading...</div>;
return (
<div>
<ul>
{items.map(({ id, statistics }) => (
<li key={id}>
Total views: {statistics.viewCount}
Total subscribers: {statistics.subscriberCount}
Total videos: {statistics.videoCount}
</li>
))}
</ul>
</div>
);
}
}
Also, you don't need an if else statement if you have a return. Either use a ternary operator or just remove the else.
Here's the sandbox if you want to take a look at it. Let me know if it helps.
You are getting data in items array, you need to set json.items in state,
this.setState({
isLoaded: true,
items: json.items
})
And then you will get statistics object data,
{
items.map(item => (
<li key={item.id}>
Total views: {item.statistics.viewCount}
Total subscribers: {item.statistics.subscriberCount}
Total videos: {item.statistics.videoCount}
</li>
))
}
Demo
I am using cdn for react
Actually I have two JSON FILE,
abc.json
[
{
"apiKey":"642176ece1e7445e99244cec26f4de1f"
}
]
reactjs.json
[
{
"642176ece1e7445e99244cec26f4de1f": {
"src": "image_1.jpg",
"id" : "1"
}
}
]
I actually want that first of all I get apiKey from the first json file and after with the help of it i like to get the value of src
1) How can I do this in React using axios?
2) Is that Possible that we can directly get the src from reactjs.json ? If yes then How?
What I tried, but it gives error..
class FetchDemo extends React.Component {
constructor(props) {
super(props);
this.state = {
images: [],
api:[]
};
//this.listImages = this.listImages.bind(this);
}
componentDidMount() {
axios.get('abc.json').then(res => {
console.log(res);
this.setState({ api: res.data });
});
axios.get('reactjs.json').then(res => {
console.log(res);
this.setState({ images: res.data });
});
}
render() {
return (
<div>
{this.state.api.map((api, index) => (
<Pictures key={index} apikeys={api.apiKey} />
))}
</div>
);
}
}
class Pictures extends React.Component {
render() {
return (
<h1>
alt={this.props.apikeys}
</h1>
{this.state.images.map((images, index) => (
<h1 key={index}> apikeys={images.+`{this.props.apikeys}`+.src} </h1>
//Error at this point
))}
);
}
}
ReactDOM.render(
<FetchDemo/>,
document.getElementById("root")
);
Using axios you are making a request. This means that your JSON would be served from a end point. If you really need to require the json file in this fashion try importing
import abc from './abc.json';
componentDidMount = () => {
this.setState({
json: abc
})
}
I'm currently trying to take some JSON data that I've received from an API and put that into a dropdown in a very simple React application.
This is my DropDown component thus far:
import React from 'react';
var values;
fetch('http://localhost:8080/values')
.then(function(res) {
return res.json();
}).then(function(json) {
values = json;
console.log(values);
});
class DropDown extends React.Component {
render(){
return <div className="drop-down">
<p>I would like to render a dropdown here from the values object</p>
</div>;
}
}
export default DropDown;
Any my JSON looks like this:
{
"values":[
{
"id":0,
"name":"Jeff"
},
{
"id":1,
"name":"Joe"
},
{
"id":2,
"name":"John"
},
{
"id":3,
"name":"Billy"
},
{
"id":4,
"name":"Horace"
},
{
"id":5,
"name":"Greg"
}
]
}
I'd like the dropdown options to correspond to the 'name' of each element, and the 'id' to be used as an element identifier when an event is triggered by selecting an option. Any advice on getting this data into a dropdown which responds to user input would be greatly appreciated.
Call the API in componentDidMount lifecycle function of your React component and then save the response in state and then render the Select dropdown
import React from 'react';
class DropDown extends React.Component {
state = {
values: []
}
componentDidMount() {
fetch('http://localhost:8080/values')
.then(function(res) {
return res.json();
}).then((json)=> {
this.setState({
values: json
})
});
}
render(){
return <div className="drop-down">
<p>I would like to render a dropdown here from the values object</p>
<select>{
this.state.values.map((obj) => {
return <option value={obj.id}>{obj.name}</option>
})
}</select>
</div>;
}
}
export default DropDown;
You could do something like this:
import React from 'react';
var values;
class DropDown extends React.Component {
constructor(){
super();
this.state = {
options: []
}
}
componentDidMount(){
this.fetchOptions()
}
fetchOptions(){
fetch('http://localhost:8080/values')
.then((res) => {
return res.json();
}).then((json) => {
values = json;
this.setState({options: values.values})
console.log(values);
});
}
render(){
return <div className="drop-down">
<select>
{ this.state.options.map((option, key) => <option key={key} >{option}</option>) }
</select>
</div>;
}
}
export default DropDown;
Basically you are initializing state and setting options to null.
You are then fetching your options when the component mounts in the browser. These values are set to your state with this.setState().
Note: It is important to make any API calls in componentDidMount() and not componentWillMount(). If you call it in componentWillMount() the request will be made twice.
Then you render these options by mapping them in your render function
JSON FILE: terrifcalculatordata.json
[
{
"id": 1,
"name": "Vigo",
},
{
"id": 2,
"name": "Mercedes",
},
{
"id": 3,
"name": "Lexus",
},
{
"id": 4,
"name": "Buggati",
},
]
CODE:
1st import json file on top:
import calculatorData from "../static/data/terrifcalculatordata.json";
2nd in render method type this code:
<Form>
<FormGroup>
<Input
type="select"
onChange = {this.changeCarmodel}
value={this.state.changeCar}
>
{calculatorData.map((caldata, index) =>
<option
key={index}
value= {caldata.id}
> {caldata.name} </option>
)}
</Input>
</FormGroup>
</Form>
How to render JSON response as dropdown list in React.
export default class ExpenseNew extends Component {
constructor(){
super();
this.state={
PickerSelectedVal : '',
accountnameMain:[],
}
}
componentDidMount(){
var account_nam=[]
fetch('your Url', {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + your token }
})
.then((response) => response.json())
.then((customerselect) => {
// alert(JSON.stringify(customerselect))
global.customerdata = JSON.stringify(customerselect)
var customername = JSON.parse(customerdata);
//alert(JSON.stringify(customername));
for (i = 0; i < customername.cus_data.length; i++) {
var dataa = customername.cus_data[i]["account_name"];
account_nam.push(dataa)
}
this.setState({accountnameMain:account_nam});
})
.done();
}
render() {
return (
<Picker
selectedValue={this.state.PickerSelectedVal}
placeholder="Select your customer"
mode="dropdown"
iosIcon={<Icon name="arrow-down" />}
onValueChange={(itemValue, itemIndex) => this.setState({PickerSelectedVal: itemValue})} >
{this.state.accountnameMain.map((item, key)=>(
<Picker.Item label={item} value={item} key={key}/>)
)}
</Picker>
)
}
}