score:1
try try catch
:
getweather = async (e) => {
try {
e.preventdefault();
const city = e.target.elements.city.value;
const country = e.target.elements.country.value;
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${api_key}&units=metric`);
const data = await api_call.json();
console.log(data);
} catch(e) {
console.log('error: ', e);
}
}
score:1
use
class app extends react.component{
getweather = async (e) => {
e.preventdefault();
const city = e.target.elements.city.value;
const country = e.target.elements.country.value;
try {
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${api_key}&units=metric`);
const data = await api_call.json();
console.log(data);
} catch(e) {
console.log(e);
}
}
score:3
just examine the status
property of the resolved promise before you try to extract the body with the .json()
method.
async function test() {
const api_call = await fetch(`https://cors-anywhere.herokuapp.com/http://example.com/fake/fake`);
console.log(api_call.status);
}
test();
score:5
regardless of using async/await
or promise chaining, the fetch
api returns a promise
containing a response
object. the response object contains a status
property which returns an http status code. before you call the .json()
method on your response
object you can check to see if res.status === 200
. for example, the openweather api will return a http status code of 200
for successful requests. so, to check if your api request was successful, you could do the following ...
class app extends react.component{
getweather = async (e) => {
e.preventdefault();
const city = e.target.elements.city.value;
const country = e.target.elements.country.value;
const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${api_key}&units=metric`);
if (api_call.status !== 200) {
// you can do your error handling here
} else {
// call the .json() method on your response to get your json data
const data = await api_call.json();
}
}
you can see more of the response
object properties and methods by viewing the mdn documentation
Source: stackoverflow.com
Related Query
- How can I handle error 404 in async/await fetch API
- How can I prevent 404 error show up in console when API link is wrong in Javascript?
- How can I handle return type for fetch async function?
- How to handle fetch API AJAX response in React
- JavaScript - How to handle 404 error in fetch?
- React Hook useEffect : fetch data using axios with async await .api calling continuous the same api
- How to use Async Await in "onDrop" of "react-dropzone" ? (Parsing error: Can not use keyword 'await' outside an Async function)
- how to handle values other than json in fetch api call
- React API Handle Error in Fetch Call : TypeError-Cannot read property 'temp' of undefined
- How to show API error handle inside of react?
- How I can pass nested promises to async await
- How can I exempt some routes to not hit 404 error if the URL don't match as exact?
- How to integrate axios api in react js with async and await using react hooks
- Can someone help me understand how async + await + useEffect work in React?
- In React, how can a parent component set state from the response an async fetch function performed in a child component?
- How can I get my fetch error to show an http status code?
- How can I mock the Geolocation API error function and !navigator.geolocation case in Jest?
- How do I redirect to error page after receiving status 404 from API call in React?
- How can I fetch base64 encoded images (string) from a URL/ API and display in ImageField or on react-admin list or show page
- How can I solve 'ENOENT' error in next.js api section?
- How to handle undefined 404 from API Call for an image which is actually loading?
- How to solve API fetch and type error in React
- how to handle async response as validation error in formik
- How can I correctly make the fetch api call in react?
- How can I show error message from API to the end-user?
- How can i handle the undefined error in React
- How to use async await in React using the axios in the API call
- reactjs: How to handle error from django api
- Handle error 404 using openweather API and ReactJS
- How can I fetch data from API url into my reactgoogle pie chart in reactjs
More Query from same tag
- How to call mapStateToProps in react component to get Redux stores
- supportedChain is deprecated, please pass networks instead
- React key prop error even after adding it
- How to create useStripe hook for react-stripe-elements
- state undefined in file tree reducer
- Restyling parent elements the React way
- How to clear error message coming from redux actions
- How to update styles dynamically in JSX
- Rails 4 + react-rails gem: Could not find generator 'react:install'
- Menu's dropdown on Chart is being offset
- CSS file is not working in react component
- React: Unable to use useContext hook
- MERN simple app CORS error issue - POST request
- react How do I check if string is empty
- Dynamically applying CSS to JSX objects
- Cannot call `this.setState` with object literal bound to `partialState` because string [1] is compatible not with string literal [2]
- Set background width (of img) to 'cover' in JSX
- Single line ellipsis in Material-UI Select and option Component
- React: Function call portal does not contain target
- Can node.js and JS Frameworks make use of ES6 out of the box?
- How to display the fetched json from redux in my react component?
- I have array data in console how can i display it in react js?
- React useEffect dependency is triggering update
- How to change the value of 1 select if there are a lot of them on the page
- Change loading state after function call
- Show all result from a list if all value is selected
- How to reset a specific method of a module with resetAllMocks in Jest?
- React Redux dispatch action
- HTMLInputElement event.target.value outputting a string event though it is a range element (typescript)
- Replace <br> tags in string with line breaks JS