How to handle api error in react and show custom log - reactjs

componentDidMount() {
let url = FormatUrl(`/user/`)
fetch(url)
.then(response => response.json())
.then(data => {
console.log(data)
}).catch(err => {
if (err){
console.log('has error')
}
})
}
Here i am trying to fetch data from a wrong api.
And it is throwing below error.
Home.jsx:20 GET http://127.0.0.1:8000/user/ net::ERR_CONNECTION_REFUSED
I
Is there any way to hide this error and display a simple message in console without throwing
exceptions.

The promise isn't rejected by the fetch API simply because it fails to reach the endpoint. What you need to do is check the response in your first .then(). You have response.status which returns the status code, or you could use response.ok which returns true if the status code is within the 200-299 interval.
A more detailed explanation can be found here

Related

Form handling in ReactJS with functional component

I have following code.
my code
What I want to is when I click on "SEND" button it show error or success messages. I tried:
.then(() =>
setAfterSendSuccess("Thank you. We will contact you shortly.")
)
.catch(() =>
setAfterSendError("Something went wrong. Please try again later")
);
But it always show green success message.
Also I have "Loading" component which should start load when I click on Send button.
For that one I tried:
{!!setFormLoading(true) && <Loading />}
The issue is with your use of the fetch api. You're expecting fetch to reject the promise if there's a 4xx or 5xx http response code, but fetch doesn't do that. It only rejects on network failures or other things that prevent the fetch from occurring at all.
So you'll need to modify your code something like the following:
fetch(`real link`, {
method: "POST",
body: JSON.stringify({ email }),
})
.then((response) => {
if (!response.ok) {
throw response;
}
return response.json(); // if you don't care about the data, you can leave this out
})
.then(() => setAfterSendSuccess("Thank you. We will contact you shortly."))
.catch(() =>
setAfterSendError("Something went wrong. Please try again later")
);
Also I have "Loading" component which should start load when I click on Send button.
Your jsx needs to be this: {formLoading && <Loading />}, and you'll need to call setFormLoading with true at the start of the submit function, and with false in the .then and .catch.

React Native get dynamic data

there is a data which is changing every second in my api and i should get it dynamically to react native screen and im using setInterval
I writed a function which is send request and get data every second and i should refresh this function and i did use setInterval but im not sure about that is this healthy? also i could not solve this because i got an error that :
Possible Unhandled Promise Rejection (id: 7):
TypeError: _this2.setState is not a function. (In '_this2.setState({
kalanzaman: res.data
})', '_this2.setState' is undefined)
My func and how am i calling it :
dynamically() {
// console.log("bom")
axios.get(`http://localhost:5000/kalanzaman`)
.then(res => {
this.setState({ kalanzaman: res.data })
})
}
.
setInterval(this.dynamically, 1000)
Which way should i use for get dynamic data to react native from my api?
Instead of Http request, you can use Websocket.
It is a two-way interactive communication session between the user's browser and a server.
for example: have a look at Socket.IO
Maybe it would be better if you write it like this:
setInterval(() => {
dynamically() {
// console.log("bom")
axios.get(`http://localhost:5000/kalanzaman`)
.then(res => {
this.setState({ kalanzaman: res.data })
}).catch((error) => {
alert('Something Error')
})
}
}, 100);
You must cath() for catching the error, and put it on componentDidMount

Api fetch responses Blob structure in React Native app

I'm consuming a web api from my React Native Android project. After updating my react-native version to 0.60.3 my response data is not returning JSON, it returns Blob data structure.
This is what I get from then(res=>{...})
Please look at the image
Screen-Shot-2019-07-18-at-17-25-10.png
The _bodyInit object was returning JSON. But now it returns Blob that I can not reach from Js code.
I tried using functions res.json(), res.text()
They worked! But this time I just got data inside the _bodyInit. I can not reach other parameters like ok, header etc.
This is what I've tried. Like I said, it works. But it returns response with just my data, not other parameters like ok, headers etc.
.then((res) => res.json())
.then((res) => {
if (res.ok) {
// No 'ok' element anymore after .json()
}
});
In the 'devtools' if I click the '_bodyInit' object. Simulator gives error below.
Screen-Shot-2019-07-18-at-17-32-49.png
Do you have any idea to solve this issue?
Thanks in advance!
ok property is with response before you call json method on it. If your response contains json, call json to serialize body as json, if response contains blob, call .blob to serialize body as blob. See more proerties of Response here.
.then((res) => {
console.log("response.ok", res.ok)
// print headers,
console.log("headers", res.headers.forEach(item=>console.log(item)))
// if response if json, call res.json
return res.json()
})
.then((res) => {
// here you will only get json data, not other properties.
console.log("json data is ", res)
});
SOLVED
I found two way to solve this problem.
Using .then() after using .json()
.then((res) => {
if (res.ok) {
res.json().then(res=>{
console.log(res)
})
} else console.log("not ok")
});
Using async and await
.then(async res => {
if(res.ok) {
const response = await res.json()
console.log(response)
} else console.log("not ok")
})
That would be great to see other solutions from you. Thanks.

Axios get data from API - React.js

I am using axios to get data from an API, I am trying to do something very simple and I have done it before.
I can see on the console that my request was made but I cant output the data or a console.log() message.
componentDidMount() {
axios.get("https://dog-api.kinduff.com/api/facts")
.then( response => {
console.log("Facts: ")
this.setState({DogFact:response.data})
})
.catch( err => {
this.setState({error:err.data.message})
})
}
The response from the api is an object with an array.
{facts["fact written here"]}
It should be very simple but If I try that:
axios.get("https://dog-api.kinduff.com/api/facts")
.then( response => {
console.log("Facts: ", response) //This wont show up on the console
this.setState({DogFact:response.facts[0]}) //This wont work.
})
I dont really understand what might be wrong.
Could someone maybe help me out?
add this line in package.json
"proxy": "https://dog-api.kinduff.com/api/"
then in your axios call change it to this:
axios.get("/facts")
.then( response => {
console.log("Facts: ", response)
this.setState({DogFact:response.facts[0]})
});

How to fetch data with axios for a placeid in Google maps and React?

I have an array in state restaurantsFetchedFromGoogle which currently stores 20 placeids previously fetched from google maps. They are stored in the array as such:
0:"ChIJTb1qU315MhMRiL7pihnMWfg"
1:"ChIJGZ0jXCCNMRMRrH8VHRAgEYE"
2:"ChIJQ5jaX8eMMRMRnRoZxl6X95w"
...
19:"ChIJQ5jaX8errrMRnRoZxl6X95w"
Now I'm trying to iterate the array with an Axios get request such as:
componentDidMount(){
navigator.geolocation.getCurrentPosition(position=>{
this.setState({geoLat:position.coords.latitude,geoLng:position.coords.longitude});
axios.get(`https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${position.coords.latitude},${position.coords.longitude}&radius=50000&keyword=recensioni&type=ristorante&keyword=cena&key=MYAPIKEY`)
.then(response => this.setState({restaurantsFetchedFromGoogle:response.data.results}));
});
this.state.restaurantsFetchedFromGoogle.map(item=>{
axios.get(`https://maps.googleapis.com/maps/api/place/details/json?placeid=${item.place_id}&key=AIzaSyCZ7rgMN34kWkGvr8Pzkf_8nkT7W6gowBA`)
.then(response => this.setState({placeId:response.data}))
.catch(err =>{
console.log(err);
console.log(err.response.data.error);
});
});
axios.get('/restaurants.json')
.then(response =>this.setState({restaurants:response.data}));
}
First and third axios request goes through but not the second one. What am I doing wrong?
Add an error handler to log the error message! That should tell you why the request is failing.
this.state.restaurantsFetchedFromGoogle.map(item=>{
axios.get('https://maps.googleapis.com/maps/api/place/details/json?placeid='+
item + '&key=MYAPIKEY')
.then(response => this.setState({placeId:response.data}))
.catch(err => {
console.log(err) //Axios entire error message
console.log(err.response.data.error) //Google API error message
})
});
Even without the .catch - you can use the chrome dev tools to see the error under the Network tab in the dev tools.
If you still have issues after - post the specific error message and I'll take a look.

Resources