Get request with fetch and react - javascript

This is probably a very dumb question, but I cant find any solution on the web, please dont bash me. I set up a create-react-app and want to display some data in a table.
This is my JSON:
[ {
"unitid" : 29,
"createddate" : 1510324778000,
"latitude" : 49.402008056640625,
"longitude" : 11.901968002319336,
"senderid" : 6,
"signalstrength" : 37
}, {
"unitid" : 34,
"createddate" : 1510563384000,
"latitude" : 49.22679901123047,
"longitude" : 12.845210075378418,
"senderid" : 8,
"signalstrength" : 0
},......
And my table needs a JSON Array with all the attributes in order to display every column correctly.
This is the code where I try to fetch the data from an endpoint of mine:
class App extends Component {
constructor(props){
super(props);
this.state = {
vehicleList: [],
};
}
componentDidMount(){
fetch('endpoint-link', {mode: 'no-cors', method: 'get'})
.then(response => response.json())
.then(result => {
this.setState({vehicleList: result.vehicleList})
console.log(result)
})
.catch(error => {
this.setState({isLoaded: true, error})
console.log(error)
});
}
render() {
const {vehicleList} = this.state;
console.log(vehicleList);.......
When I open the Devtools in Chrome, go for "Network" I can see that the endpoint is known and the data is found, but somehow the fetch method is not loading the JSON into the Array.

Your JSON doesn't have a vehicleList property. It just has the array of vehicles. So you need to put that in your state:
this.setState({vehicleList: result})

The problem is this -> ...{mode="no-cors"...}
See this post in order to fix it: Handle response - SyntaxError: Unexpected end of input

Related

how to access obj from json in React?

Api Respose :-
[
{
"System Name": "Name1",
"Primary Sensor": "WWWW",
"Mean Wind Speed": "6.23 m/s",
"Status": 1,
"mws_number": 44,
"DRR (%)": "100",
"drr_number": 100
},
{
"System Name": "Name 2",
"Primary Sensor": "SSSS",
"Mean Wind Speed": "4.2 m/s",
"Status": 2,
"mws_number": 6,
"DRR (%)": "100",
"drr_number": 100
}
]
My Code ->
class Home extends Component {
state = {
items:[],
isLoading:false
}
componentDidMount() {
// api
fetch('http://api.url', {
method: 'POST',
body:
JSON.stringify({"Authentication":'token'})
}).then(data => data.json() )
.then(res =>{
this.setState({isLoading:true,
items:res,}
)
});
}
render() {
return (
<>
{console.log(this.state.items[0])} // getting o/p - first obj of array
{console.log(this.state.items[0].Status)} // getting Error undef Status
{console.log(this.state.items.Status[0])} // same error undef status
</>
)
export def ....
This is my complete piece of code... I can't add api url as it is not public api :(
I want to access this data inside of the array =>(Status, System Name, etc)
how can i fetch this !!
Here, console.log(this.state.items[0]); is getting called two times;
- When the page first loads and API request is not finished.
- After the API request finishes and you call this.setState
Solution would be to check that items' length is greater than 0 before trying to use it. Try changing console.log(this.state.items[0]); to this:
if (this.state.items.length > 0) { console.log(this.state.items[0].Status); }
I would suggest you to use componentWillMount() instead of componentDidMount() becuase componentWillMount() happens before render while componentDidMount() happens after the first render.May be that help.

React grabbing JSON response property

I'm very new to React. I have a JSON response that is being returned to me VIA WebAPI 2.
I would like to display only parts of this reply, for example if i only want to display the title
I have implemented the following code, but when view title it shows up as undefined
App.js
class App extends React.Component {
constructor(props){
super(props);
this.state = {reply: ""}
this.callAPI = this.callAPI.bind(this);
}
componentDidMount(){
this.callAPI();
}
callAPI(){
fetch('http://localhost:51092/api/COM',{
method:'get',
headers:{'Content-Type':'application/json'}
}).then(function(response){
return response.json();
}).then(responseData => {
this.setState({reply:responseData});
console.log("REPONSEDATA-----"+responseData);
console.log(responseData.title);
});
}
render(){
return(
<div>
</div>
);
}
}
Update 1
callAPI(){
fetch('http://localhost:51092/api/COM',{
method:'get',
headers:{'Content-Type':'application/json'}
}).then(response =>{
return response.json().then(responseData => {
this.setState({reply:responseData});
console.log("RESPONSE----"+JSON.stringify(responseData));
console.log(responseData.title);
});
});
}
API JSON Response
[{
"fileVer": {
"type": "specific",
"fileId": {
"type": "specific",
"internalId": 1,
"externalId": null
},
"internalVersion": 2,
"externalVersion": null,
"versionSortKey": "0"
},
"title": "1576544 Alberta Ltd._Annual Returns_2012-01-03",
"extension": "pdf",
"logicalSize": "47872",
"sizePrecision": "exact",
"createdAtUtc": "2019-05-27T15:22:41.510Z",
"lastAccessedAtUtc": "2019-07-10T21:00:28.029Z",
"lastWrittenAtUtc": "2019-05-27T15:17:48.000Z",
"changedAtUtc": "2019-05-27T15:17:48.000Z",
"fileGuid": "{881D8975-84B9-4A73-9AFF-F0C61C94FE90}",
"checksumMD5": "24f6badff8b70783697e0052fc4a7fe6",
"fileMissing": false,
"contentIsVolatile": false
}][{
"fileVer": {
"type": "specific",
"fileId": {
"type": "specific",
"internalId": 2,
"externalId": null
},
"internalVersion": 3,
"externalVersion": null,
"versionSortKey": "0"
},
"title": "1576544 Alberta Ltd._By-Law #1_",
"extension": "pdf",
"logicalSize": "951046",
"sizePrecision": "exact",
"createdAtUtc": "2019-05-27T15:22:42.000Z",
"lastAccessedAtUtc": "2019-07-10T21:02:54.062Z",
"lastWrittenAtUtc": "2019-05-27T15:16:28.000Z",
"changedAtUtc": "2019-05-27T15:16:28.000Z",
"fileGuid": "{F8B54DB0-7E9F-4F0F-8ABA-D03C1DE4FF8C}",
"checksumMD5": "ffe728ef1a87f0cec7737b6d224bb50d",
"fileMissing": false,
"contentIsVolatile": false
}]
Not sure what im doing wrong here, ive used Ajax a lot so maybe im confusing what can be done with react and fetch
Update 2
So it seems that this may be a single object, and not an array of objects.
console.log("RESPONSE----"+JSON.stringify(responseData));
var arr = [];
console.log("KEYS"+Object.keys(responseData));
Object.keys(responseData).forEach(function(key){
console.log(responseData[key]);
arr.push(responseData[key]);
When i try to access responseData[key] i end up getting a single letter, and not a property from the json response
This pushes me to believe that this is not an array of objects but a single object
you should use JSON.stringify when printing full json response and if part of the object is string (eg... response.title then its ok but if not you can try .toString() or JSON.stringify)
callAPI(){
fetch('http://localhost:51092/api/COM',{
method:'get',
headers:{'Content-Type':'application/json'}
}).then(function(response){
return response.json().then((responseData)=>{
this.setState({reply:responseData});
console.log("REPONSEDATA----"+JSON.stringify(responseData));
console.log(responseData.title);
return responseData
});
}

Unable to parse JSON data returned via fetch method in React

Before marking it duplicate would be great if you please read once. I really, searched on this.
I am writing a React app to generate meme. I can connect the REST API successfully and able to fetch data. The problem is, while trying to parse data, I am getting an error which summarize that I am trying to access an undefined object, which I am not.
I tried same code statically (without React's rendering flavor) in another editor and it is working fine.
Here is my code,
class App extends React.Component{
state = {memes : []};
componentDidMount(){
fetch(
`https://api.imgflip.com/get_memes`
).then(
(response) => {
if(response.ok){
return response;
}else{
console.log('no response');
}
}
).then(data => data.json()).then(data => {
console.log(data); //This is getting printed fine
// console.log(data.memes[1].name); //un-commenting this is throwing error that 'Cannot read property '1' of undefined'
this.setState({memes:data.memes});
});
}
render(){
if(this.state.memes.length > 0){
//For this I am getting error
//Uncaught TypeError: Cannot read property 'length' of undefined
console.log('array length is : ' + this.state.memes.length);
}else{
//This is printed fine
console.log('Here array length is : ' + this.state.memes.length);
}
return (
<div>
<MemeImage/>
</div>
);
}
}
export default App;
The problem is, during the second time rendering (after data is fetched) React assuming data.memes doesn't exist which is absurd for me. As per my console log, it exists.
EX:
data:
memes: Array(100)
0: {id: "112126428", name: "Distracted Boyfriend", url: "https://i.imgflip.com/1ur9b0.jpg", width: 1200, height: 800, …}
1: {id: "87743020", name: "Two Buttons", url: "https://i.imgflip.com/1g8my4.jpg", width: 600, height: 908, …}
2: {id: "102156234", name: "Mocking Spongebob", url: "https://i.imgflip.com/1otk96.jpg", width: 502, height: 353, …}
3: {id: "129242436", name: "Change My Mind", url: "https://i.imgflip.com/24y43o.jpg", width: 482, height: 361, …}
I checked the demo data as below from the respective website. As per this, data.memes[0].name is perfectly valid. I tried it and it worked.
{
"success": true,
"data": {
"memes": [
{
"id": "61579",
"name": "One Does Not Simply",
"url": "https://i.imgflip.com/1bij.jpg",
"width": 568,
"height": 335,
"box_count": 2
}
]
}
}
But really, clueless what is happening during React rendering, that it is fetching the 'data' object but can't access properties inside. Any help regarding what I am failing to understand about React's rendering would be very much appreciated.
Use this code
this.setState({memes:data.data.memes});
When you console.log your data
console.log(data)
You get
{
data: Object
success: true
}
So you need to go inside data to access the memes,

Firebase orderByValue().equalTo() is not a function (Node JS)

My database has the following structure:
"groupA" : {
"applications" : {
"applicationID_132" : {
"status" : "accepted"
},
"applicationID_423" : {
"status" : "declined"
},
"applicationID_562" : {
"status" : "accepted"
}
}
}
I am trying to retrieve the snapshot of applications with "accepted" status (to be able to skip fetching all applications) by:
return admin.database().ref('groupA').child('applications').orderByValue('status').equalTo('accepted')
.once('value')
.then(acceptedApplicationsSnapshot => {
Doesn't seem to work, tried orderBy and orderByValue as well. What might be missing or what is the better way to handle this case?
Thank you for any help!
Try using child.orderByChild().value()
In your case:
return admin.database().ref('groupA').child('applications').orderByChild('status').equalTo('accepted')
.once('value')
.then(acceptedApplicationsSnapshot => {
You could use orderByValue() as well, but first you would need to get the Reference which you want to order - function does not accept parameter.
How to use orderByValue()?
.child(..) returns a Reference in your case that is applications if you want to use orderByValue than you would need to get reference to 'status' before doing that, eg:
admin.database().ref('groupA').child('applications').child('status').orderByValue() and then you would apply one of the data filtering methods eg.
.equalTo('accepted')...

Firebase Pagination using startAt with value and Key not working

I'm trying to setup a pagination for a search page in mobile app developed in ionic3. The search results always fetched only the first 5 values even if the key is provided.
I tried to put a different key but still the issue exists.
Please find the code below
this.storeListRefss$ = this.db.list(`/productList/` + this.storeId + `/`, {
query: {
orderByChild: 'product_name_search',
limitToFirst: 5,
startAt: { value: 'milk', key: '-L2Z8INhE8mFA4fWwiGk' },
endAt: self.searchValue + "\uf8ff"
}
});
this.storeListRefss$.subscribe((result) => {
result.forEach((element) => {
self.searchResults.push(element);
});
console.log(this.searchResults);
});
This is the sample json data iam pulling from the firebase
{
"-L2Z8Gvp-T5O3r46dQO4" : {
"product_desc" : "",
"product_img" : "",
"product_name" : "2-POCKET PAPER FOLDER",
"product_name_search" : "2-pocket paper folder",
"product_reg_price" : "0.7900",
"product_sales_price" : "0.7900",
"product_upc" : "718103177610",
"status" : 1
},
"-L2Z8Gvp-T5O3r46dQO5" : {
"product_desc" : "",
"product_img" : "",
"product_name" : "3 MUSKETEERS BITES",
"product_name_search" : "3 musketeers bites",
"product_reg_price" : "1.9900",
"product_sales_price" : "1.9900",
"product_upc" : "040000422471",
"status" : 1
}
}
You're on an old version of AngularFire which doesn't support the second argument for startAt() or endAt() in the query API.
You have two options: upgrade to the new api or create a reference and pass it into the list() method. I recommend upgrading to the new version 5 API which is much simpler. But I'll detail both below.
Option 1 - Create a reference instead of using the Query API
constructor(private db: AngularFireDatabase) {
const ref = db.database.ref(`/productList/` + this.storeId);
const query = ref
.orderByChild('product_name_search')
.limitToFirst(5)
.startAt('milk', '-L2Z8INhE8mFA4fWwiGk')
.endAt(self.searchValue + "\uf8ff");
const list$ = db.list(query);
}
Option 2 - Upgrade to the new API
constructor(private db: AngularFireDatabase) {
const list$ = db.list(`/productList/` + this.storeId, ref => {
return ref
.orderByChild('product_name_search')
.limitToFirst(5)
.startAt('milk', '-L2Z8INhE8mFA4fWwiGk')
.endAt(this.searchValue + "\uf8ff");
}).valueChanges();
}

Categories

Resources