Reputation: 207
When I try to fetch some data from weather API using fetch
request in React application its not getting the response from the api below are the code which I wrote:
import React from 'react'
class App extends React.Component {
constructor() {
super();
this.state = {
datatemp: {},
loading:true
}
}
componentDidMount() {
loading:true;
fetch('https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22').then(response => response.json()).then(data => {
this.setState({
datatemp: data,
loading: false
});
});
}
render()
{
console.log(this.state.datatemp);
return (
<p>ddd</p>
)
}
}
export default App;
all the help will be much appreciable.
Upvotes: 2
Views: 8526
Reputation: 1674
Look bro I have changed url to test! Just check it
import React from "react";
class App extends React.Component {
constructor() {
super();
this.state = {
datatemp: {},
loading: true
};
}
componentDidMount() {
fetch("https://jsonplaceholder.typicode.com/posts")
.then(response => response.json())
.then(data => {
this.fetchedData(data);
});
}
fetchedData = data => {
this.setState({
datatemp: data,
loading: false
});
for (let i = 0; i < this.state.datatemp.length; i++) {
console.log(this.state.datatemp[i].body);
}
};
render() {
return <p>Good Luck</p>;
}
}
export default App;
Upvotes: 1
Reputation: 3238
what is the function of loading:true;
Remove it your code works
import React from 'react'
class App extends React.Component {
constructor() {
super();
this.state = {
datatemp: {},
loading:true
}
}
componentDidMount() {
fetch('https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22').then(response => response.json()).then(data => {
this.setState({
datatemp: data,
loading: false
});
});
}
render()
{
console.log(this.state.datatemp);
return (
<p>ddd</p>
)
}
}
export default App;
Upvotes: 0
Reputation: 328
It's happening because of CORS.
Try replacing your API with any Dummy API which Doesn't Restrict CORS. for Example: "https://jsonplaceholder.typicode.com/todos/1"
import React from 'react';
class App extends React.Component {
constructor() {
super()
this.state = {
datatemp: {},
loading: true
}
}
componentDidMount() {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(data => {
this.setState({
dataTemp: data,
loading: false
}, () => {
console.log("data: ", this.state.dataTemp);
})
})
}
render() {
return (
<p>ddd</p>
)
}
}
Upvotes: 0