I am new to React and this threw up while trying to map some data from API. I have set the state to an array but still this error comes up.
import React, { Component } from 'react';
import axios from 'axios';
class Test extends Component {
state = {
articles: [],
}
componentDidMount() {
axios.get('https://newsapi.org/v2/top-headlines?country=us&apiKey=ef678d80cc70495184c2bf95d4576c9b')
.then(response => {
const articles = response.data;
this.setState({ articles });
})
}
render() {
return (
<div>
<ul>
{this.state.articles.map(article => <li><a href={`${article.url}`}>{article.title}</a></li>)}
</ul>
</div>
)
}
}
export default Test;
Try changing
const articles = response.data;
to
const articles = response.data.articles;
Its because the api returns an JSON Output with response in articles key.
import React, {Component} from 'react';
import axios from 'axios';
class Test extends Component {
state = {
articles: [],
}
componentDidMount() {
axios.get('https://newsapi.org/v2/top-headlines?country=us&apiKey=ef678d80cc70495184c2bf95d4576c9b')
.then(response => {
const articles = response;
this.setState({articles:articles.articles});
}) }
render() {
return (
<div>
<ul>
{this.state.articles.map(article =>
<li><a href={`${article.url}`}>{article.title}</a>
</li>)}
</ul>
</div>
) }
}
export default Test;
import React, {Component} from 'react'; import axios from 'axios';
class Test extends Component {
state = {
articles: [],
flag:false
}
componentDidMount() {
axios.get('https://newsapi.org/v2/top-headlines?country=us&apiKey=ef678d80cc70495184c2bf95d4576c9b')
.then(response => {
const articles = response.data;
this.setState({articles,flag:true});
}) }
render() {
let data = flag === false?"Loading...":this.state.articles.map(article => <li><a href={`${article.url}`}>{article.title}</a></li>)
return (
<div>
<ul>
{data}
</ul>
</div>
) }
}
export default Test;
Related
I am trying to fetch all the posts data from the admin site to show on my frontend but for now it is only print first value instead of all the data's.
I want solution on this, here is my code below.
import React, {Component} from 'react';
import { Link } from 'react-router-dom';
import { Stack } from './common/contentstack-api/api.js';
export default class App extends Component{
constructor() {
super()
this.state = { loading : true, result: null}
}
componentDidMount () {
var Query = Stack.ContentType("posts").Query()
.toJSON()
.find()
.then((result) => {
console.log(result);
this.setState({loading : false, result:result})
})
.catch((error) => {
console.log(error)
})
}
renderList (result) {
return (
<main>
<div className="media-body ">
{
this.state.result.map((value, index) => {
return (
<div className="article-metadata">
<ul>
<li>{ value[index].title}</li>
</ul>
</div>
)
})
}
</div>
</main>
)
}
render () {
const {loading, result} = this.state
return (this.state.loading) ? <h1>loading...</h1> : this.renderList(result[0])
}
}
I would like to get data from a json using an url with reactJS but it does not work.
The url where I want to get data is the following : url
Here is my code :
import React from "react";
import { render } from "react-dom";
import axios from "axios";
class App extends React.Component {
constructor() {
super();
this.state = { member: [] };
}
memberList(list) {
const memberList = list.map((member, index) => {
return (
<li>
{member.name} {member.age}
</li>
);
});
return <ul>{memberList}</ul>;
}
render() {
console.log(this.state.member);
return (
<div>
<button onClick={this.getJson}>Get json</button>
{this.memberList(this.state.member)}
</div>
);
}
getJson = () => {
const url =
"https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json";
axios.get(url).then((res) => {
// console.log(res.data);
this.setState(res.data);
});
};
}
render(<App />, document.getElementById("root"));
and the project is there : my project
Thank you for your help !
hey i am new in the field and want to display the state using the map and i am not able to do so
and there is no problem in the api call through axios so ignore it
my code is
import React, { Component } from 'react';
import axios from 'axios';
const url ='https://www.reddit.com/r/space.json';
class Apicall extends Component {
state={
posts:[],
subr:'space'
};
componentDidMount(){
this.getReddit();
}
getReddit=async()=>{
console.log('getredddit called sir ');
try {
let response=await axios.get(`https://www.reddit.com/r/${this.state.subr}.json`);
let posts=response.data.data.children.map(obj=>obj.data)
this.setState({posts:posts},()=>{console.log(this.state.posts);
})
} catch (error) {console.log(error);}}
render() {
let controlItems=this.state.posts.map(post=>{<h1 id={post.id}>{post.title}</h1>});
return (
<div>
<h1>{`/r/${this.state.subr}`} </h1>
{controlItems}
</div>);
}
}
export default Apicall;
You were iterating wrong on your data. response.data.data.children should be replaced with response.data.children. Implicit return of et controlItems=this.state.posts.map(post=>{{post.title}}); is also wrong.
import React from "react";
import "./styles.css";
export default function App() {
return (
<div className="App">
<Apicall />
</div>
);
}
class Apicall extends React.Component {
state = {
posts: [],
subr: "space"
};
componentDidMount() {
this.getReddit();
}
getReddit = async () => {
console.log("getredddit called sir ");
try {
let response = await fetch(
`https://www.reddit.com/r/${this.state.subr}.json`
);
response = await response.json();
console.log(response);
let posts = response.data.children.map(obj => obj.data);
this.setState({ posts: posts }, () => {
console.log(this.state.posts);
});
} catch (error) {
console.log(error);
}
};
render() {
let controlItems = this.state.posts.map(post => (
<h1 id={post.id}>{post.title}</h1>
));
return (
<div>
<h1>{`/r/${this.state.subr}`} </h1>
{controlItems}
</div>
);
}
}
i am new in react. Can anyone help me that How to call API using react js and show the response in page. I am trying the following code but getting error.
export default class UserList extends React.Component {
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const users = res.data;
this.setState({users});
})
}
render() {
return (
<ul>
{this.state.users.map(user => <li>{user.name}</li>)}
</ul>
)
}
}
Hi you missed to declare the state. you need to declare it in UserList Component. Please follow this example:
import React from 'react';
import axios from 'axios';
export default class UserList extends React.Component {
state = {
users: []
};
componentDidMount() {
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
const users = res.data;
this.setState({users});
})
}
render() {
return (
<ul>
{this.state.users.map(user => <li>{user.name}</li>)}
</ul>
)
}
}
Good day! I wanna to do dynamic dropdown menu, witch get data from server. So, if menu item clicked i wanna to fetch data from server and render result in list. Like this:
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {fetchData} from 'actions'
class MenuItem extends Component {
constructor(props) {
super(props);
this.state = {
isOpened: false,
}
}
toggleOpen() {
this.props.fetchData(); // Here is fetching data using redux-thunk
this.setState({isOpened: !this.state.isOpened});
}
render() {
const {data} = this.props;
return (
<a href="#" className="left-menu__link"
{...( this.state.isOpened && {
className: "left-menu__link is-opened"
} )}
onClick={(e) => {
e.preventDefault();
this.toggleOpen.bind(this)();
}}>
<ul className="left-menu__sub-level">
{!R.isEmpty(data) && data.map((item) =>
<li item={item} key={item.id}/>)}
</ul>
)
}
const mapStateToProps = state => ({
data: getData(state), // get data from state
});
const mapDispatchToProps = {
fetchData
};
export default connect(mapStateToProps, mapDispatchToProps)(MenuItem)
So can you tell me which is the best way to do this?
Here I have changed some of the code. I hope it will help
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {fetchData} from 'actions'
class MenuItem extends Component {
constructor(props) {
super(props);
this.state = {
isOpened: false
}
this.handleClick = this.handleClick.bind(this)
}
handleClick(e) {
e.preventDefault()
this.setState({isOpened: !this.state.isOpened})
this.props.fetchData().then((response) => {
....
....
})
}
render() {
const {data} = this.props;
const className = !this.state.isOpened ? 'left-menu__link' : 'left-menu__link is-opened'
return (
<a href="#" className={className}
onClick={this.handleClick}>
<ul className="left-menu__sub-level">
{!R.isEmpty(data) && data.map((item) =>
<li item={item} key={item.id}/>)}
</ul>
)
}
}
const mapStateToProps = state => ({
data: getData(state), // get data from state
});
const mapDispatchToProps = {
fetchData
};
export default connect(mapStateToProps, mapDispatchToProps)(MenuItem)