React Displaying List of Items from Ajax request - ajax

I am learning React and I am trying to display a list of users from and ajax call. I am getting an unexpected token error from CodePen when I add the line
export default Users;
When I remove the line there are no more errors but the list of users is not being displayed.
My code:
function GetUsers(project){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
console.log(data);
callback(null, data);
},
error: function (error) {
console.log(data);
callback(error, {});
}
});
}
function UserList(users) {
const userItems = users.map((user) =>
<ul>
<li>
{ user.name }
</li>
<li>
{ user.email }
</li>
<li>
{ user.phone}
</li>
</ul>
);
return (userItems);
}
class Users extends Component {
componentDidMount() {
GetUsers(null, function (err, data) {
if (err)
{
console.log(err);
}// do something
this.setState({ users: data })
}.bind(this))
}
render() {
return(
<UserList user = {this.state.users} />
);
}
}
if (document.getElementById('root')) {
ReactDOM.render(<Users />, document.getElementById('root'));
}
Here is my code.
Thank you for any and all help!

Problem 1 in AJAX call
function GetUsers(project){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
console.log(data);
callback(null, data);
},
error: function (error) {
console.log(data);
callback(error, {});
}
});
}
$.ajax is asynchronous call, that means it doesn't returns directly any value (how it could if it is fetching the results from the internet) it Just creates another function which will call success and error when completed.
That's why we need to wrap it with callbacks
function GetUsers(project, resolve = () => {}, reject = () => {}) {
}
Problem 2 in mount
componentDidMount() {
GetUsers(null, function (err, data) {
if (err)
{
console.log(err);
}// do something
this.setState({ users: data })
}.bind(this))
}
This code is completely wrong, it has even syntax error so not worth to discuss it in details.
We need to call our new function and pass success callback for mutating the state
GetUsers(null, users => {
this.setState({ users });
});
In this way we will call GetUsers wait for it's results and only after that we will mutate the state with new result
3 problem in component creation
React component's don't have state by default, you need to infer the state from constructor so we need to change initialization to
constructor(props) {
super(props);
this.state = {
users: false
};
}
otherwise you will get Cannot call setState of undefined as state is not automatically created for performance purposes and all components are Pure by default.
I have created a working sandbox here

in
function GetUsers(project){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
return data;
},
error: function (error) {
console.log(error);
return {};
}
});
}
--
success: function (data) {
return data;
}
doesn't do what you think it does. return data isn't really returning the data... anywhere.
You need to have a callback.
function GetUsers(project, callback){
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function (data) {
callback(null, data)
},
error: function (error) {
callback(error, {})
}
});
}
class Users extends Component {
componentDidMount() {
GetUsers(null, function (err, data) {
if (err) // do something
this.setState({ users: data })
}.bind(this))
}
render() {
return(
<UserList user = {this.state.users} />
);
}
}
you can also Promise-ify things to simplify the logic

Related

Leaflet mapping: Assign object to fetch promise for local GeoJSON file

I am looking to assign as an object a Fetch API promise from a local GeoJSON file.
Here is the code
fetch("data/sites.geojson")
.then(function(response) {
return response.json();
})
.then(function(data) {
L.geoJSON(data, {
pointToLayer: styles_sites
}).addTo(map);
});
};
I tried the call back method, as advised here
Saving fetched JSON into variable
(EDIT) New code, but there is still a missing formal parameter
function getData("data/sites.geojson", cb) {
fetch("data/sites.geojson")
.then(function(response) {
return response.json();
})
.then(function(data) {
L.geoJSON(data, {
pointToLayer: styles_sites,
onEachFeature: function (feature, layer) {
layer.on('mouseover', function() {
layer.openPopup(layer.bindPopup("<b>"+feature.properties.nombre+"</b>"))
});
layer.on('mouseout', function() {
layer.closePopup();
});
layer.on('click', function () {
layer.bindPopup("<b>Nombre: </b>"+feature.properties.nombre+"<br><b>Barrio: </b>"+feature.properties.barrio+"<br><b>Tipo: </b>"+feature.properties.tipo+"<br><b>Ubicacion: </b>"+feature.properties.ubicacion+"<br><b>Correo: </b>"+feature.properties.contacto);
});
}
}).addTo(map);
.then(function(result) {
cb(result);
});
});
};
getData("data/sites.geojson", function (data) {
return console.log({data});
});
Most probably just incorrect syntax of your callback function:
// Use either arrow function
getData("data/sites.geojson", (data) => {
return console.log({data});
});
// or standard function
getData("data/sites.geojson", function (data) {
return console.log({data});
});
I found the way to work this out by adding within the fetch function, what I originally wanted to do on the map.
This was to add a L.controlLayer using the geojson as overlay.
This is the code that made it work:
let sites = getData()
.then((function(data) {
L.geoJSON(data, {
pointToLayer: styles_sites,
onEachFeature: function LayerControl(feature, layer) {
var popupText = "<b>" + feature.properties.nombre + "<br>";
layer.bindPopup(popupText);
category = feature.properties.tipo;
// Initialize the category array if not already set.
if (typeof categories[category] === "undefined") {
categories[category] = L.layerGroup().addTo(map);
layersControl.addOverlay(categories[category], category);
}
categories[category].addLayer(layer);
layer.on('mouseover', function() {
layer.openPopup(layer.bindPopup("<b>"+feature.properties.nombre+"</b>"))
});
layer.on('mouseout', function() {
layer.closePopup();
});
layer.on('click', function () {
layer.bindPopup("<b>Nombre: </b>"+feature.properties.nombre+"<br><b>Barrio: </b>"+feature.properties.barrio+"<br><b>Tipo: </b>"+feature.properties.tipo+"<br><b>Ubicacion: </b>"+feature.properties.ubicacion+"<br><b>Correo: </b>"+feature.properties.contacto);
});
}
}).addTo(map);
}));
Actually it comes from one of your answer on another post ghybs.

chrome popup extension not sending data on the api.php file

I am using chrome popup extension but no data is sent to the php file named api.php.I have searched on stackoverflow and found ajax related content but nothing is working.here is my popover.js file which uses ajax.I used $_POST['data'] to grab the data in api.php file
var api_url = "https://localhost/psol/api.php";
window.onload = function () {
$("#checkout_btn").click(function () {
chrome.runtime.sendMessage({
'btnClicked': true
}, function () {});
});
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
console.log(request);
if (request.message === "show-loading") {
$(".psol-button").addClass('hide');
$(".psol-loader").removeClass("hide");
}
if (request.message === "hide-loading") {
$(".psol-button").removeClass('hide');
$(".psol-loader").addClass("hide");
}
if (request.message === "post-cart") {
console.log(request.data);
alert(JSON.stringify(request.data));
chrome.runtime.sendMessage({
'postCartDone': true,
'redirectTo': api_url
}, function () {});
$.ajax({
url: api_url,
type: "POST",
data: request.data,
// data:{name:'uzair'},
success: function (result) {
// alert("all done");
console.log(1, result);
}
}).done(function (result) {
console.log(2, result);
if (result.cartCount === 0) {
alert('There are no items in cart to checkout');
}else {
alert("this is also redirect");
}
});
}
});
};

In My react native app i am not able to setState the ajax response

constructor(){
super();
this.state = {
data: ''
}
}
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
this.setState({data: response }); // here i am getting error
console.log(this.state.data);
})
.catch(function (error) {
console.log(error);
});
In My react native app i am not able to setState the ajax response.. When i am trying to update the state here it throws error and execute catch function... I don't know why it happens can you please give me the quick suggestion
First of all, please read the difference between arrow functions and normal function declarations.
this.setState({}) will only work if you use arrow functions () => or you can do it the old fashion way by saving this inside a variable like so:
fetchData() {
const self = this;
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
self.setState({data: response }); // here i am getting error
console.log(self.state.data);
})
.catch(function (error) {
console.log(error);
});
}
I, however, prefer to use an arrow function instead as it's much simpler.
ex:
fetchData() {
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(response => this.setState({data: response }) )
.catch(console.log);
}
P.S: You can also bind this using the .bind(this) method.
That's because you use the ES2015 syntax to create your function, which doesn't bind the context by default.
Use an arrow function instead :
.then((reponse) => {
console.log(response);
this.setState({data: response });
console.log(this.state.data);
}

Iterate inside the sequlize result set

I need to iterate over result set from the sequelize result. I have a code that works, but I think something is wrong with it, and it should not be done this way.
I have a feeling this is a blocking code.
This is the code that works:
models.Project.findAll({
where: {ProjectId: projectId}
})
.then(function (projects) {
//Iteration is here
var projectList = [];
projects.forEach(function (res) {
projectList.push(res.dataValues.PartId);
});
//then bulk lookup for the result
models.Customers.findAll({
where: {'id': {in: [projectList]}}
}).then(function (customers) {
reply(customers).code(200);
}, function (rejectedPromiseError) {
reply(rejectedPromiseError).code(401);
});
//reply(sameparts).code(200);
}, function (rejectedPromiseError) {
reply(rejectedPromiseError).code(401);
});
This iteration parts is done:
projects.forEach(function (res) {
projectList.push(res.dataValues.PartId);
});
And then this code is executed as another query:
models.Customers.findAll({
where: {'id': {in: [projectList]}}
}).then(function (customers) {
reply(customers).code(200);
}, function (rejectedPromiseError) {
reply(rejectedPromiseError).code(401);
});
How can I rearange it so it uses Promises?
EDIT (Possible solution):
After playing a bit, I believe I have implemented promises.
getAll: function (request, reply) {
var projectId = request.params.projectid;
var promises = [];
var post;
models.SamePart.findAll({
where: {ProjectId: projectId}
})
.then(function (sameparts) {
//Iteration is here
sameparts.forEach(function (res) {
promises.push(
Promise.all([
models.Parts.findAll({where: {id: res.dataValues.PartId}})
]))
});
//Bulk lookup for the parts that were marked as identical
return Promise.all(promises);
}).then(function (completepartslist) {
reply(completepartslist).code(200);
});
Is this a correct approach? It seems that completepartslist contains many unwanted objects, including Promise stuff. How can I flatten it, so to avoid complex for loops?
If you are using .then(), then you are, in all probability, already using promises.
Your original, working code doesn't appear to be blocking.
Your final getAll() looks like it should simplify to :
getAll: function (request, reply) {
models.SamePart.findAll({
where: { ProjectId: request.params.projectid }
}).then(function (sameparts) {
return Promise.all(sameparts.map(function (res) {
return models.Parts.findAll({ where: { id: res.dataValues.PartId } });
}));
}).then(function (completepartslist) {
reply(completepartslist).code(200);
});
}
However, you need to add error handling back in.
even more simplified
getAll: function (request, reply) {
models.SamePart.findAll({
where: { ProjectId: request.params.projectid }
}).reduce(function (completepartslist, sameparts) {
return models.Parts.findAll({ where: { id: sameparts.PartId } }).
then(function(res){
completepartslist.concat(res)
});
}), []);
}).then(function (completepartslist) {
reply(completepartslist).code(200);
});
}

How to read data of $http request inside controller from a service?

I'm trying to save the return value of $http service inside my controller, but I get "undefined" like response
In my controller, I call a service that uses the $http:
//this returns undefined
vm.user_instruments = instruments.getInstruments();
My service:
function instruments($http){
this.getInstruments = function(){
$http.get('url/').
then(function(response) {
/*this console.log print the response,
but this value I can't get it in my controller*/
console.log(response.data);
return response.data;
}, function(error) {
return error.data;
});
}
}//end service
So, what am I doing wrong? My purpose is that the controller be ignorant of any details of HTTP
Several problems . First your service function isn't returning anything .... return $http from it.
this.getInstruments = function(){
// return the request promise
return $http.get('url/').
then(function(response) {
return response.data;
}, function(error) {
return error.data;
});
}
Then in controller assign the scope inside a promise callback:
instruments.getInstruments().then(function(data){
vm.user_instruments = data
});
you have two options to do this:
1. return the promise to the controller and use the promise in the controller
function service ($http) {
this.request = function () {
return $http.request({ /*...*/ });
};
}
function controller (service) {
service.request().then(function (resp) {
console.log(resp);
});
}
2. send callback to service and return the data to the callback
function service ($http) {
this.request = function (callback) {
return $http.request({ /*...*/ }).then(function (resp) {
callback(null, resp);
}, function (err) {
callback(err);
});
};
}
function controller (service) {
service.request(function (err, resp) {
if (err) return console.log(err);
console.log(resp);
});
}
the popular option is to use promises, so use option 1 :)
Try this way
Service:
function instruments($http){
this.get = function(callback){
$http.get('/url').success(function(res){
callback(res);
});
}
} /* end service */
Controller:
instruments.get(function(res){
vm.instruments = res;
});
It should work.
PS: typed in mobile.

Resources