I am making an API call in react where from a cryptocurrency API data will be fetched. But I want to get the data for specific cryptocurrencies. I am trying to define some logic inside the fetch request but it's not working. I am trying to add "bitcoin" and "ethereum" as a paramters inside the request.
Code:
import React, { Component } from 'react';
import './App.css';
import Crypto from './Component/Crypto';
class App extends Component {
constructor(){
super();
this.state={
data: [
{
name:'',
id:'',
symbol:'',
price_usd:'',
percent_change_1h:'',
percent_change_24h:'',
percent_change_7d:'',
isLoading:true
},
]
}
this.fetchData=this.fetchData.bind(this);
}
fetchData=()=>{
fetch('https://api.coinmarketcap.com/v1/ticker/?limit=3')
.then((response)=>{
const wanted=['ethereum','bitcoin']
const r=response.data.filter(currency=>
wanted.includes(currency.id))
this.setState({
data:r,
isLoading:false
})})
.catch(err=>alert("error"));
}
componentDidMount(){
this.fetchData();
this.interval = setInterval (() => this.fetchData (), 10*1000)
}
render() {
return (
<div className="App">
<div className="App-header">
{this.state.isLoading?<Loading/>:
<Crypto data={this.state.data}/>
}
</div>
</div>
);
}
}
const Loading=()=>{
return(
<div>
loading...
</div>
);
}
export default App;
try this way :
fetch('https://api.coinmarketcap.com/v1/ticker/?limit=3')
.then((resp) => resp.json())
.then(function(data){
const wanted=['ethereum','bitcoin']
const filtered=data.filter(currency=>{ return wanted.includes(currency.id)
});
console.log(filtered);
}).catch(err=>alert('error'));
learn more about fetch api here : https://scotch.io/tutorials/how-to-use-the-javascript-fetch-api-to-get-data
Related
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 });
[enter link description here][1]I am fetching API in react. I am able to see data in console but it is not appearing in JSX. I want to see Data id, name and value. But it is not appearing in browser.
[1]: https://codesandbox.io/s/late-thunder-456qp?file=/src/App.js
import React from 'react';
import axios from 'axios'
import './App.css';
class Main extends React.Component {
constructor(props) {
super(props)
this.state = {
users: [],
error: ''
}
}
componentDidMount(){
axios.get('https://jsonplaceholder.typicode.com/users')
.then( response => {
console.log(response);
this.setState({users: response.data})
})
.catch(error =>{
console.log(error);
})
}
render() {
const { users } = this.state
return (
<div>
<h2> Main Page</h2>
<p class="para-text"> Data from API</p>
{
users.length ?
users.map(post => <div key ={ users.id }> { users.name} </div>) : null
}
</div>
);
}
}
export default Main;
when mapping you named the key to your map as post and therefore when displaying them in jsx you must refer to that key
attached is a forked version of your sandbox https://codesandbox.io/s/late-thunder-456qp?file=/src/App.js
import "./styles.css";
import React from "react";
import axios from "axios";
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [],
error: ""
};
}
componentDidMount() {
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((response) => {
this.setState({ users: response.data });
})
.catch((error) => {
console.log(error);
});
}
render() {
const { users } = this.state;
return (
<div>
<h2> Main Page</h2>
<p class="para-text"> Data from API</p>
{users.length > 0
? users.map((post) => <div key={post.id}> {post.name} </div>)
: null}
</div>
);
}
}
export default Main;
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 }));
}
So im trying to set a variable with the data im getting from the API.
when im console logging it into my browser everything works fine but when im trying to set my variable on React the variable ending up undifeind.
can someone tell me what am i missing here?
this is my code :
import React from 'react'
let news
function getNews () {
fetch(
'https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9'
)
.then(res => res.json())
.then(data => {
news = data
return news
})
}
getNews()
class NewsApi extends React.Component {
render () {
return <div />
}
}
export default NewsApi
Your getNews function is async. You should use state to save your data. So, as soon as the data fetched, you can use the data in your component.
import React from 'react';
class NewsApi extends React.Component {
constructor(props) {
super(props);
this.state = {
news: []
};
this.getNews = this.getNews.bind(this);
}
componentDidMount() {
this.getNews()
}
getNews() {
fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9')
.then(res => res.json())
.then((data) => {
this.setState({news:data.articles});
});
}
render() {
console.log(this.state.news)
return (
<div></div>
);
}
}
export default NewsApi;
try this : It outputs what you want.
** Notes:
Fetch is Async functions, means, it has to be called inside (for example) life cycle method like componentDidMount.
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
news: []
};
}
componentDidMount() {
fetch(
"https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
)
.then(response => response.json())
.then(data => this.setState({ news: data.articles }));
}
render() {
console.log(this.state.news);
return <div />;
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Here is a live example (You can see console output also)\
Please look at the snippet below for an example implementation.
Some key points:
Try to do your data fetching in componentDidMount()
Use state and this.setState()
This will cause an automatic rerender after the data is fetched.
Handy for working with asynchronous function calls: these tools make it easy to use data in components without knowing when it will become available and help eliminate the undefined issue you were having.
class NewsApi extends React.Component {
state = {
articles: []
};
componentDidMount() {
fetch(
"https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
)
.then(res => res.json())
.then(data => data.articles)
.then(articles => {
this.setState({ articles });
});
}
render() {
return (
<div>
<h1>Articles</h1>
<ArticleList articles={this.state.articles} />
</div>
);
}
}
const ArticleList = props => (
<div>
<ol>
{props.articles.map((article, index) => (
<div key={index}>
<li>{article.title}</li>
<br />
</div>
))}
</ol>
</div>
);
function App() {
const appStyle = {
fontFamily: "sans-serif",
textAlign: "center"
};
return (
<div className="App" style={appStyle}>
<NewsApi />
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Can someone tell me what is wrong with my code below? I am making an HTTP request to Darksky API using 'superagent' and then trying to display the result in an h2 which isn't working. I tried logging it to console and it works perfectly but if I am trying to display it on the page it doesn't work. Could someone help me out pls, I am new to react and not sure what is going wrong.
import React, { Component } from "react";
import "./Body.css";
import Request from "superagent";
class Body extends Component {
constructor() {
super();
this.getData = this.getData.bind(this);
}
getData() {
var url = this.props.apiUrl;
Request.get(url)
.then(response => {
return(JSON.stringify(response.currently.summary));
})
.catch(error => {});
}
render() {
<div>
<h2>
{this.getData()}
</h2>
</div>
}
}
export default Body;
This is the other file where I am importing Body.js :-
import React, { Component } from "react";
import Body from "./Body";
import "./App.css";
class App extends Component {
render() {
return <Body
apiUrl="https://api.darksky.net/forecast/42a9693aecf45c358afbda0022c5cf65/28.5355,77.3910" />;
}
}
export default App;
You need to set your data in the state of the component, it fire new render:
constructor() {
super();
this.getData = this.getData.bind(this);
this.state = {data: {}}
}
componentDidMount() {
var url = this.props.apiUrl;
Request.get(url)
.then(response => this.setState({data: JSON.stringify(response.currently.summary)}))
.catch(error => {});
}
render(){
console.log("your data", this.state.data);
return <div>test</div>;
}
And work with this data with this.state.data.
I advise you to change getData() function to componentDidMount mehtod.
You should use a life cycle method(componentDidMount) with the use of state. It is recommended to make HTTP calls inside the componentDidMount() method.
constructor() {
super();
this.state = {
result: ''
};
}
componentDidMount(){
var url = this.props.apiUrl;
Request.get(url)
.then(response => {
this.setState({
result: JSON.stringify(response.currently.summary)
});
})
.catch(error => {});
}
render() {
<div>
<h2>
{this.state.result}
</h2>
</div>
}