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.
Related
Good day!
Im having a weird experience using formik today,
I am currently working on an app that uses formik to handle forms and will do an API request inside the onSubmit() function of formik.
Every thing went well except when i use API request and wait for it's callback.
Somehow the things inside the function of onSubmit will work properly but the API callback value does not return unless i perform a UI Change in the app itself (like pressing random spots on my screen to trigger ui change).
Here is a look of my onSubmit function of formik
onSubmit={values => {
console.log("before")
let response = FunctionWithApiRequest(values);
console.log("after")
response.then((res) => {
console.log(res)
})
}}
and here is my function with api request inside
const FunctionWithApiRequest = (credentials) => {
return fetch(`${AppConfig.HOSTNAME}/v2/auth/signup`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(credentials)
})
.then((response) => response.json())
.then((responseJson) => {
return responseJson
})
.catch((error) => {
console.log(error)
});
}
The return "responseJson" will only appear inside the onsubmit function when i perform a UI Change (like clicking random spots in my react native screen)
i was wondering what is the problem and what cause the bug.
Thank you for your response in advance.
Possibly you can do this in a separate function with await and async.For instance
async handleSubmit(){
let {credentials} = this.state
let data = await this.props.FunctionWithApiRequest(credentials)
this.setState({returnedData: data})
}
And now in your textInput/formik
onSubmit={()=>this.handleSubmit()}
I assume you have made the request api function in actions.file, not in the same file.Am i right?So what i have done is just put await before call.Which means next line will execute only when you have response returned.Comment down if you have any issue.
It was caused by the haul bundler, when you enable dugging mode.
I am trying to make a POST call to a PHP file with axios.
loginHandler = () => {
var params = new URLSearchParams();
params.append('User', this.state.inputUsername);
params.append('Pwd', this.state.inputPassword);
var callAction = process.env.REACT_APP_API_ENDPOINT + 'LoginHandler.php';
axios.post(callAction, params)
.then(res => {
const message = res.data;
console.log(message);
})
.catch(function (error) {
// handle error
console.log(error);
})
}
But everything I try seems to give me a "Request aborted" error.
However, doing axios requests from any other component except the LoginForm component seems to work.
Is there anything wrong with my axios call? I just copy/pasted it from a component that works, and it has no issues there.
The method was called on the "Submit" button onClick, which forced the page to reload before the request was completed.
Moving it to the form
<form onSubmit ={(event) => this.loginHandler(event)} >
and adding event as parameter on loginHandler, and this line of code
event.preventDefault();
got it working eventually.
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
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]})
});
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.