Reputation: 827
I noticed some strange behaviour from chrome on a simple GET request from a Public API. I tested the same code on Mozilla and I get no errors, but Chrome keeps throwing me errors about this. Can someone help me say why my GET call isn't working on chrome?
import React, { Component } from 'react';
import './App.css';
import {getPokemon} from './services';
class App extends Component {
constructor(props) {
super(props);
this.state = {
name : "",
}
}
onClick(){ getPokemon().then((response) => { this.setState({ name: response.name })
})
}
render() {
return (
<div className="App">
<button onClick={(e) => this.onClick(e)}> Click me</button>
<h2> {this.state.name}</h2>
</div>
);
}
}
export default App;
Fetch call:
export const getPokemon = () => {
return fetch(`https://pokeapi.co/api/v2/pokemon/blastoise`).then((response) => {
if(response.statusText === 'OK') {
return response.json();
}
throw new Error('Network response was not ok.');
})
}
React & Console error:
Btw I already remove all my chrome files and reinstalled them.
Any tips?
Upvotes: 0
Views: 1526
Reputation: 736
First of all you are using fetch method and you might be knowing that you cant check response.status
as fetch only fails when a network error is encountered or CORS is mis-configured on the server side kind of error. For redirection and all other errors it still comes as success
Please read it : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Right way of actual success checking for fetch method is below : Check for response.ok
.then(function(response) {
if(response.ok) {
console.log("success");
}
throw new Error('Network response was not ok.');
}
Upvotes: 0
Reputation: 1197
This is what it returns
{
body: ReadableStream,
bodyUsed: false,
headers: {},
ok: true,
status: 200,
statusText: "",
type: "cors",
url: "https://pokeapi.co/api/v2/pokemon/blastoise/"
}
So you are probably looking for either ok
or status
Upvotes: 0
Reputation: 2109
Response.statusText is experimental and the Response
in Chrome has statusText
property as an empty string. A simple change would be to update your conditional statement to:
if(response.status === 200)
Upvotes: 1