ReactJS axios POST call to PHP - Request Aborted error - reactjs

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.

Related

Axios API call returns a 404 on page render, but still returns api objects in terminal

I am using axios to make an api call to an api found on Apihub for a next JS app.
here is the code for the function to make the call to provide a list of property JSON objects.
export const baseUrl = "https://zillow56.p.rapidapi.com"
export const fetchApiListsingsCustom = async (url) => {
const { data } = await axios.get((url), {
method: 'GET',
headers: {
'X-RapidAPI-Key': '328713ab01msh862a3ad609011efp17e6b4jsn0e7112d5ee9a',
'X-RapidAPI-Host': 'zillow56.p.rapidapi.com'
}
});
data.then((res) => {
console.log(res);
})
.catch((error) => {
console.error(error);
});
return data.json();
}
When rendering the page I'm attempting to inject the response's data to dynamically create a list of apartment listings.
I'm trying to use getServerSideProps so that the data is already available by the time a user requests the page. After fetching the data, I want to also print them in the terminal to validate it's success.
export default function Home({ propertiesCustomdata })
export async function getServerSideProps() {
const propertiesCustom = await fetchApiListsingsCustom(`${baseUrl}`)
const propertiesCustomdata = propertiesCustom.json()
return {
props: {
propertiesCustomdata
}
}
}
The problem is, I seem to be getting a 404 error from the axios call, before the page gets a chance to load. When I access this I get a 404 error but I also manage to receive some contents of the call the API was to make.
My apologies if this is unclear, but this is all I know to report on this so far.
Studying async and await, fetch, and axios. Very confusing.

How to call a custom React error component inside axios interceptor

I want to show/call a custom react error component. Below is my code snippet. I am getting error since my axios interceptor is neither a react component nor a custom Hook.
axios.interceptors.response.use((response) => {
if (response.config.parse) {
//perform the manipulation here and change the response object
}
return response;
}, (error) => {
//Want to call the component here
return Promise.reject(error.message);
});
I don't think you can render a component in an axios interceptor.
The interceptor will intercept every response you make, and if there is an error do something with the error.
Meaning React would have no way of knowing what to render in which part of the DOM based on an error on any response from axios. Here is a good explanation of how interceptors work and good use cases for them
If you want to render an error message to the user then don't intercept the response. Just wait until the response errors (in a normal request not an interceptor) then pass that error to your own error component.
In practice that might look something like the below
function apiQuery (url) {
const [error, setError] = useState(null);
const [api, setApi] = useState(null);
axios.get(url)
.then(function (response) {
// handle success
setApi(response.data)
})
.catch(function (error) {
// handle error
setError(error)
})
return { api, error }
}
Now you have access to the error response which you can pass into your own error component
const api = apiQuery('/users')
// pass error into your bespoke component
if (api.error) return <Error error={error}/>

not able to fetch api response

I have written an API where I am generating data in JSON format.
Now I am calling same API on react frontend. If response is generated we will display a success page else we will divert to same page. So I have written these code when I submit user id and password on submit event validateLogin API has been called, but I am not able to execute body of API response.
onSubmit = async => {
const { user_mail, user_pass1 } = this.state
const payload = { user_mail, user_pass1}
api.validateLogin(payload).then((res) =>{
alert('Success');
})
.catch((err) =>{
alert('Failed');
})
}
Here nothing is executing. Can you please help me to execute response body?

Axios not retreiving data from REST service

Im using React with axios to read some data from my backend.
I have a BetBuilder js using axios to read like this:
componentDidMount() {
axios.get('http://localhost:8080/api/matches/')
.then(response => {
console.log("Dentro do didmount");
this.setState({ matches: response.data._embedded.matches });
console.log(this.state.matches);
console.log("Dentro do didmount");
});
Everything works fine here. So in my render method i pass this data to a Match component:
var matches = this.state.matches.map(match =>
<Match key={match._links.self.href} match={match}/>
);
In my Match.js class, I try to retrieve other data with axios. But it just doesnt work. In my debug it never enters on the response function.
const awayUrl = this.props.match._links.away.href;
const homeUrl = this.props.match._links.home.href;
axios.get("http://localhost:8080/api/matches/4/away")w
.then(response => {
console.log("Dentro do away");
this.setState({ away: response.data._embedded });
console.log(this.state.away);
console.log("Dentro do away");
})
.catch((error) => {
console.log("error",error)
});
What Im missing? Theres something on the Axios lifecycle that i cant use it in the same request? Why this axios.get method is never called, and dont throws any exception too?
Thanks

How do I make an HTTP request in react-redux?

I am just getting started with react and I'm a bit lost. I'm trying to make a login page and make a http post request. Right now I'm just trying to get any type of HTTP request working, so I'm using request bin and I found this basic action in the docs for an npm package (https://www.npmjs.com/package/redux-react-fetch):
export function updateTicket(ticketId, type, value){
return {
type: 'updateArticle',
url: `http://requestb.in/1l9aqbo1`,
body: {
article_id: ticketId,
title: 'New Title'
},
then: 'updateTicketFinished'
}
}
So, after writing an action, what do I do? How do I actually get my app to call on and use that action? The docs for the npm package mention something about setting a state in my store, is that something I need to set up first?
You can try any of the following. I have used both fetch and axios they work amazingly well. Yet to try superagent.
For making requests you can either use fetch with
fetch-polyfill for compatibility across all browsers (link)
Axios library. (link)
Superagent with promises.(link)
If you use fetch you would need to use polyfill since it is not supported in IE and safari yet. But with polyfill it works pretty well. You can check out the links for how you can use them.
So what you would doing is in your action creator you can call an API using any of the above.
FETCH
function fetchData(){
const url = '//you url'
fetch(url)
.then((response) => {//next actions})
.catch((error) => {//throw error})
}
AXIOS
axios.get('//url')
.then(function (response) {
//dispatch action
})
.catch(function (error) {
// throw error
});
So that was for the API call, now coming to the state. In redux there is one state which handles your app. I would suggest you should go through redux basics which you can find here . So once your api call succeeds you need to update your state with the data.
Action to fetch data
function fetchData(){
return(dispatch,getState) =>{ //using redux-thunk here... do check it out
const url = '//you url'
fetch(url)
.then (response ) => {dispatch(receiveData(response.data)} //data being your api response object/array
.catch( error) => {//throw error}
}
}
Action to update state
function receiveData(data) {
return{
type: 'RECEIVE_DATA',
data
}
}
Reducer
function app(state = {},action) {
switch(action.types){
case 'RECEIVE_DATA':
Object.assign({},...state,{
action.data
}
})
default:
return state
}
}

Resources