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
Related
I'm learning about fetch and promises on reactjs, and sometimes I had a problem with my internet connection. So is it possible for me to create my own API but still can use or call it with fetch() function?
You could use mocking tools to mock the APIs.
One such example is https://mockoon.com/
You can setup a local server and use fetch() to pull from localhost.
This is an example Node server:
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('test')
})
const server = app.listen(8081, () => {
console.log("Example app up")
})
You can then fetch() from localhost:8081
We can locally read the JSON data using fetch API in JavaScript. If you are using react hooks, place it inside the useEffect hook.
Check the console in this code sample link
Code: Your data.json will contain the sample JSON data.
fetch("./data.json")
.then(function (response) {
return response;
})
.then(function (data) {
return data.json();
})
.then(function (finalData) {
console.log(finalData);
})
.catch(function (err) {
console.log("Fetch problem show: " + err.message);
});
I want to integrate React with Django REST API for my ecom website but for some reason that does not work. I really do not know what I missed. Any input is welcomed.
Please see the code below.
REACT
Home.js (this is the code for products)
const loadAllProducts = () => {
getProducts()
.then((data) => {
if(data.error) {
setError(data.error); //box filled with data error
console.log(error); // message "error"
} else {
setProducts(data); // box filled with data product
}
});
loadAllProducts();
};
coreapicalls.js (here I want to fetch the data)
import { API } from "../../backend.js";
export const getProducts = () => {
return fetch(`${API}product`, { method: "GET" })
.then(response => response.json())
.catch((err) => console.log(err));
};
.env (I have both of my servers running, the url and symbol "/" are correct.)
REACT_APP_BACKEND = http://localhost:8000/api/
My compiler returns no specific error.
./src/core/Home.js
Line 16:11: 'loadAllProducts' is assigned a value but never used no-unused-vars
./src/core/Card.js
Line 26:11: 'getAredirect' is assigned a value but never used no-unused-vars
DJANGO (settings.py, Django does give me JSON data on the localhost:8000/api/product/)
'api',
'api.category',
'api.product',
Best,
Rok.
I went into chrome devtools and saw a "cors error" under network. I forgot to run "pip install django-cors-headers" . The configuration on the DJANGO REST API for corsheaders was correct.
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
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
I am building my first React Native app and use Redux for the data flow inside my app.
I want to load some data from my Parse backend and display it on a ListView. My only issues at the moment is that for some reason, the request that I create using fetch() for some reason isn't actually fired. I went through the documentation and examples in the Redux docs and also read this really nice blog post. They essentially do what I am trying to achieve, but I don't know where my implementation differs from their code samples.
Here is what I have setup at the moment (shortened to show only relevant parts):
OverviewRootComponent.js
class OverviewRootComponent extends Component {
componentDidMount() {
const { dispatch } = this.props
dispatch( fetchOrganizations() )
}
}
Actions.js
export const fetchOrganizations = () => {
console.log('Actions - fetchOrganizations');
return (dispatch) => {
console.log('Actions - return promise');
return
fetch('https://api.parse.com/1/classes/Organization', {
method: 'GET',
headers: {
'X-Parse-Application-Id': 'xxx',
'X-Parse-REST-API-Key': 'xxx',
}
})
.then( (response) => {
console.log('fetchOrganizations - did receive response: ', response)
response.text()
})
.then( (responseText) => {
console.log('fetchOrganizations - received response, now dispatch: ', responseText);
dispatch( receiveOrganizations(responseText) )
})
.catch( (error) => {
console.warn(error)
})
}
}
When I am calling dispatch( fetchOrganizations() ) like this, I do see the logs until Actions - return promise, but it doesn't seem to actually to fire off the request. I'm not really sure how how I can further debug this or what resources to consult that help me solve this issue.
I'm assuming that Redux is expecting a Promise rather than a function.. Is that true?
If so, I think your return function may not be working.
You have a new line after your return, and it's possible JavaScript is (helpfully) inserting a semicolon there.
See here: Why doesn't a Javascript return statement work when the return value is on a new line?