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>
)
}
}
Related
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 !
I'm trying to update state in React.js using an API call, as I need to show some of the data to the end user.
The api call works through localhost:5001 and is stored in Firebased functions.
import React, { Component } from 'react'
import './Table.css';
class Table extends Component {
constructor (props)
{
super(props);
this.state = {
stocks: []
};
}
componentDidMount() {
fetch('localhost:5001') // Removed for stackoverflow //
.then((response) => response.json())
.then(stockList => {
this.setState =
({ stocks: stockList });
});
}
render() {
return (
<div className='table'>
<h1 id='title'>Companies</h1>
{this.state.stocks.map(stocks => <h2 key={stocks.symbol}> {stocks.companyName}</h2>)}
</div>
)
}
}
export default Table;
Here is a snippet of the API call:
{"symbol":"AAPL","companyName":"Apple Inc"}
setState is a function, so you should call it, rather that assign values to it:
this.setState({ stocks: stockList });
Hi I am working on a react app with Routing and HOC. I expect to see a page but i get page not found when i know the page is there.
in componentDidMount this.setState, data is shown as undefined but in the HOC wrapper i see the data arrive from the server.
Before I wrapped the page in HOC i could see it rendering content so I know the content exists.
Here is my Page component which is being called via a Route :
import React, { Component } from "react";
import WithBackend from "./WithBackend";
class Page extends Component {
constructor(props) {
super(props);
this.state = { model: null };
}
render() {
if (this.state.model != null) {
return (
<div className="container">
<div className="row">
<div className="col-md">
<h1>{this.state.model.title}</h1>
</div>
</div>
</div>
);
} else {
return (
<div>
<h2>Home</h2>
</div>
);
}
}
componentDidMount() {
const data = this.props.getPage("1");
console.log(data);
this.setState({
model: data,
});
}
}
export default WithBackend(Page);
Here is the HOC component WithBackend: I am not sure if i should be setting the state on this class on in the class that is being wrapped.
When i debug the code in the getPage method, in the setState part i see the data being populated from the backend server.
import React from "react";
import ContentService from "./ContentService";
const WithBackend = (WrappedComponent) => {
class HOC extends React.Component {
constructor() {
super();
this.contentService = new ContentService();
this.getPage = this.getPage.bind(this); // <-- Add this
}
getPage(id) {
this.contentService
.getPage(id)
.then((response) => response.json())
.then((data) => {
this.setState({ model: data });
})
.catch((e) => {
console.log(e);
});
}
render() {
return <WrappedComponent getPage={this.getPage} {...this.props} />;
}
}
return HOC;
};
export default WithBackend;
and here is the contentService which only returns a promise:
class ContentService {
pageUrl = process.env.REACT_APP_BASE_URL + "/pages/";
getPage(id) {
const path = this.pageUrl + id;
const fetchPromise = fetch(path, {
method: "GET",
});
return Promise.resolve(fetchPromise);
}
}
export default ContentService;
Could anyone please advice what i am doing wrong?
Thanks in advance.
getPage is an asynchronous method, that should return a promise:
getPage(id) {
return this.contentService
.getPage(id)
.then((response) => response.json())
.catch((e) => {
console.log(e);
});
}
And then
componentDidMount() {
this.props.getPage("1").then(model => this.setState({ model }));
}
Hi I'm trying to make a simple news app to learn react. Keep getting an error which I don't understand. Why app worked fine with a json placeholder api. However now it's displaying the error props.stories.map is not a function.
Here is my code.
import NewsList from './components/NewsList';
class App extends React.Component {
constructor() {
super()
this.state = {
stories: [],
}
}
componentDidMount() {
fetch(`https://newsapi.org/v2/top-headlines?country=gb&apiKey=${API_KEY}`)
.then(res => res.json()
.then(data => this.setState({stories: data}))
)
}
render(){
const { stories } = this.state
return (
<div className="App">
<NewsList stories={stories} />
</div>
);
}
}
import Story from './Story'
import styled from 'styled-components'
const NewsList = props => {
return(
<NewsListWrapper>
{
props.stories.map(story => (
<Story story={story} />
)
)
}
</NewsListWrapper>
)
}
import React from 'react';
import styled from 'styled-components';
export const Story = props => (
<StoryWrapper>
<h2>{props.story.title}</h2>
<p>{props.story.author}</p>
<p>{props.story.articles}</p>
</StoryWrapper>
)
I have console.log the api response and the data was being received fine. It's simply when I use this other api response.
And I've hidden my api_key just for this post, so it's not issues with that.
Thanks for any advice.
In New API documentation (https://newsapi.org/docs/endpoints/top-headlines) you can see that your request return object of form
{
status: string
totalResults: number
articles: Array
}
So you need to set to stories not data but data.articles:
fetch(`https://newsapi.org/v2/top-headlines?country=gb&apiKey=${API_KEY}`)
.then(res => res.json()
.then(data => this.setState({stories: data.articles}))
)
Try this,
import NewsList from './components/NewsList';
class App extends React.Component {
constructor() {
super()
this.state = {
stories: [],
storiesData:[]
}
}
componentDidMount() {
fetch(`https://newsapi.org/v2/top-headlines?country=gb&apiKey=${API_KEY}`)
.then(res => res.json()
.then(data => this.setState({stories: data}))
)
}
render(){
const { stories } = this.state
return (
<div className="App">
<NewsList stories={stories} />
</div>
);
}
}
import Story from './Story'
import styled from 'styled-components'
const NewsList = props => {
console.log(props.stories);
this.setState({storiesData:props.stories});
return(
<NewsListWrapper>
{
this.state.storiesData.map(story => (
<Story story={story} />
)
)
}
</NewsListWrapper>
)
}
import React from 'react';
import styled from 'styled-components';
export const Story = props => (
<StoryWrapper>
<h2>{props.story.title}</h2>
<p>{props.story.author}</p>
<p>{props.story.articles}</p>
</StoryWrapper>
)
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;