Axios not retreiving data from REST service - reactjs

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

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.

ReactJS axios POST call to PHP - Request Aborted error

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.

Axios interceptor not working when initialized in a react Higher Order Function

I have a Component which makes a axios get
Component <using axios instance> {
componentDidMount(){
axios.get('myurl.jn').then(ingredients => { <wrong url>
}).catch( error => {
console.log(error) // dosent even show here as we donot propagate the error
})
}
}
export default hoc(Component,axiosInstance)
Higher Order Funcfor Component
const ErrorHandler = (WrapperComponent, axios) => {
return class extends Component {
componentDidMount(){
axios.interceptors.request.use(req => {
console.log(req) // none
this.setState({error : null});
return req;
});
axios.interceptors.response.use(res => res,(error) => {
console.log(error) // none
this.setState({error : true});
});
}
I tried adding logger and breakpoints to all the places in the hoc which uses the axios instance but to no effect nothing gets called .
The only place the interceptor is picked up in the place where i create the instance why and how do we solve this. The console for browser throws 404 but not caught by interceptor.
I am very new to react and axios just learning for past week please pardon if not following any proper guidelines

Any way at all to specify a callback to wrap the response with?

So I am trying to develop a search bar component in a React application where you can type in a users last name and that request will go to the Behance API and pull up that users data.
I am stuck on this:
axios
.get(API_URL + 'users?q=' + 'matias' + '&client_id=' + API_KEY + '&callback=')
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
alert(error.message);
});
I have tried wrapping the above in a const userSearch = () => {}, but that takes me a step farther from my goal. With the above I actually do get 200 statuses, but there is the CORS issue. I just can't seem to put together a callback that is not undefined in there, nevermind that this is a search bar implementation so I am going to have to refactor the above. I was just wanting to see some data returned.
One of the nicest things in Axios, is the seperation between request argument.
For example, the url should be only URL: API_URL + '/users'.
The parameters you want to pass, should be sent as an object.
The promise of the axios get, is the callback you are looking for.
Therefore, your request should look like this:
axios.get(API_URL + 'users', {
params: {
q: 'matias',
client_id: API_KEY,
}
})
.then(response => {
- success callback actions -
})
.catch(error => {
- error callback actions -
});
So I had refactored my axios code and I was still getting CORS errors, but after reading a couple of blogs online saying that with fetch() and jQuery you could get around that, in particular this SO article: Loading Data from Behance API in React Component
I actually duplicated Yasir's implementation like so:
import $ from 'jquery';
window.$ = $;
const API_KEY = '<api-key>';
const ROOT_URL = `https://api.behance.net/v2/users?client_id=${API_KEY}`;
export const FETCH_USER = 'FETCH_USER';
export function fetchUser(users) {
$.ajax({
url: `${ROOT_URL}&q=${users}`,
type: 'get',
data: { users: {} },
dataType: 'jsonp'
})
.done(response => {})
.fail(error => {
console.log('Ajax request fails');
console.log(error);
});
return {
type: FETCH_USER
};
}
And sure enough, no more CORS error and I get back the users data in my Network > Preview tabs. Not very elegant, but sometimes you are just trying to solve a problem and at wits end.

React won't respond to any request

I am working on an app where I am making a request and trying to send my data back to react via fetch.
So far here's my router file:
router.get('/', (req, res, next) => {
console.log('I got here before request..... >>>>>>>>>');
request(`https://rest.coinapi.io//v1/exchangerate/BTC?apikey=${API}`, (error, response, body) => {
console.log('I got here..... >>>>>>>>>');
if(error){
console.log('error >>>>>>', error);
}
console.log(response.body);
});
});
And i included to main server,js
// include routes
var routes = require('./routes/index');
app.use('/', routes);
app.listen(3000, () => {
console.log('Listening to port 3000...');
});
And then finally I sent my data to react:
class MainApp extends Component{
constructor(props){
super(props);
this.state = {
data: null
}
}
componentDidMount() {
this.getInitial();
}
getInitial() {
fetch('/')
.then(resp => resp.json())
.then(data => this.setState({
data: data.rates
}))
.then(() => console.log('this is is a state >>>>+++', this.state))
.catch(err => console.log(err))
}
render(){
return (
<div>
<h1>HELLO WORLD FROM REACT CLIENT FRONTEND! PP</h1>
<p>{this.state.data}</p>
</div>
);
}
}
For some reason I am not getting any console.log on my express when i run my code and I am getting this error: SyntaxError: Unexpected token < in JSON at position 0
Any idea what am doing wrong why I can't change the state? and why the request doesn't run?
The problem isn't React. The data is in JSON form, which has bunch of keys, value inside. You need to use a map function to render the {this.state.data}. You can not call a entire JSON object like that. You have to dig deep in the JSON Object and get whatever you need.
Let's assume you have the following JSON data.
{
"crypto": {
"BTC": {
"name": "bitcoin",
"current_price": "$6592.3"
}
}
}
you can't just say {this.state.data}. In this case you probably will do something like this {this.state.data.crypto.BTC.name} to get the name of the BTC-crypto symbol. Using the map function you can get name and prices of all the crypto symbol assuming there are more.
actually your code on server does not send any response. When you are using console.log on server - you will see that messages in terminal, where you execute command "nodejs app.js" or some other to start server. To send response, depending on node framework, you are using, you should do something like this:
router.get('/', (req, res, next) => {
...
res.setHeader('Content-Type', 'application/json');
res.send(SOME_JSON);
});
Also as i see, your server is listening port 3000, but fetch sends request not there

Resources