How to show data in React Table with structure {_id:" xx",timestamp:"xx" ,message:"{"temperature:22","humi":45}" }? - node.js

React-Table
I have made an axios.get request to the back-end which in turn gives a large data-set from mongodb. The
structure of data returned is :
[
1: {_id: "5dd3be2ecf55e1ec388f502b", timestamp: 1574157870567, message: "{"temperature":58,"humidity":59,"pressure":"1 bar"}"}
2: {_id: "5dd3be2ecf55e1ec388f502a", timestamp: 1574157870067, message: "{"temperature":78,"humidity":79,"pressure":"1 bar"}"}
...
]
I want to show it to react-table.The id and timestamp is being displayed but the temperature and other variable are not being displayed.The message is string.How can I parse such amount of data at back-end to convert message into object?
Back-end code
router.get('/viewData',async(req,res) =>{
collection.find({},{_id:0,timestamp:0}).sort({timestamp:-1}).limit(400).toArray(function (err, resultantData) {
if (err)
throw err;
//var storedDataArray ;
//var gotData=[];
//var index =0;
//storedDataArray=resultantData;
//console.log(storedDataArray)
// storedDataArray.forEach(element => {
// gotData[index]=JSON.parse(element);
// console.log(gotData[index])
// index++;
// })
// console.log(gotData.length);
res.status(200).json(resultantData);
});
Is there any way to show temperature and other quantities in react table?
React-Table
class deviceData extends Component {
constructor(props) {
super(props)
this.state = {
dataList:[],
data : ' '
};
}
componentDidMount(){
const url="http://localhost:5000/api/data/viewData";
fetch (url,{
method: "GET"
}).then(response=> response.json()).then(result=>{
console.log(result);
this.setState({
dataList : result,
});
});
}
render() {
const columns =[
{
Header:"Message ID",
accessor:"_id",
sortable: true,
filterable: false,
style:{
textAlign: "left"
},
width: 300,
maxWidth: 100,
minWidth: 100,
},
{
Header:"Time Stamp",
accessor:"timestamp",
width: 300,
maxWidth: 100,
minWidth: 100,
},
{
Header:"Temperature",
id:'temperature',
filterable: false,
accessor: 'temperature'
},
{
Header:"Pressure",
id:'pressure',
filterable: false,
accessor: 'pressure'
},
{
Header:"Humidity",
id:'humidity',
filterable: false,
accessor: 'humidity'
},
]
return(
<div className="ReactTable">
<ReactTable
columns={columns}
data={this.state.dataList}
defaultPageSize={10}
className="-striped -highlight"
>
</ReactTable>
<div id={"#"+ this.props.id} ></div>
</div>
);
}
}
[![React-Table][1]][1]
Backend Response
[
{
"_id": "5dd3be2fcf55e1ec388f502c",
"timestamp": 1574157871067,
"message": "{\"temperature\":93,\"humidity\":94,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2ecf55e1ec388f502b",
"timestamp": 1574157870567,
"message": "{\"temperature\":58,\"humidity\":59,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2ecf55e1ec388f502a",
"timestamp": 1574157870067,
"message": "{\"temperature\":78,\"humidity\":79,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2dcf55e1ec388f5029",
"timestamp": 1574157869567,
"message": "{\"temperature\":88,\"humidity\":89,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2dcf55e1ec388f5028",
"timestamp": 1574157869066,
"message": "{\"temperature\":99,\"humidity\":100,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2ccf55e1ec388f5027",
"timestamp": 1574157868567,
"message": "{\"temperature\":38,\"humidity\":39,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2ccf55e1ec388f5026",
"timestamp": 1574157868067,
"message": "{\"temperature\":82,\"humidity\":83,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2bcf55e1ec388f5025",
"timestamp": 1574157867566,
"message": "{\"temperature\":76,\"humidity\":77,\"pressure\":\"1 bar\"}"
}
]

Convert string back to object by using parse()
ex: var object = JSON.parse(str);
Important thing is to define column with correct accessor. Try this one:
const columns = [
{
Header: "Id",
accessor: "_id"
},
{
Header: "timestamp",
accessor: "timestamp"
},
{
Header: "Temprature",
accessor: "message.temprature"
},
{
Header: "humidity",
accessor: "message.humidity"
},
{
Header: "pressure",
accessor: "message.pressure"
}
];
And Use it in React-table like this:
<ReactTable
data={loans} // Instead of loans, use variable where you store your response
columns={columns}
defaultPageSize={10}
sortable={true}
/>

I think you can try with adding a headers in your fetch method
fetch (url,{
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
}
})
It will ensure your response is JSON
N.B. Try your url with postman first, setting those headers and see whether result is JSON or not, if it is JSON I believe my code will help you, if it is not a JSON return try to change your back-end code to ensure it return JSON using postman

Related

Unable to retrive ordered job list from Google Transcoder API

i'm using the node.js client library of google transcoder api. I'm able to retrive a paginated list of some jobs, but i'm not able to order elements by start date. Here my codes:
const { TranscoderServiceClient } = require('#google-cloud/video-transcoder').v1;
class TranscoderApiController {
constructor() {
this.projectId = process.env.GOOGLE_CLOUD_PROJECT;
this.location = process.env.TASK_LOCATION;
}
async getEntries(req, res, next) {
const params = {
pageSize: req.query.pageSize ? parseInt(req.query.pageSize) : 10,
pageToken: req.query.pageToken,
filter: req.query.filter,
orderBy: req.query.orderBy
}
const client = new TranscoderServiceClient();
const result = await client.listJobs({
parent: client.locationPath(this.projectId, this.location),
pageSize: params.pageSize,
orderBy: 'createTime.seconds'
}, {
autoPaginate: false
});
if (result.length == 3 && result[2] != undefined) {
return result[2];
} else {
return result[1];
}
}
}
module.exports = new TranscoderApiController();
When i call the getEntries method i receive the following error:
"3 INVALID_ARGUMENT: The request was invalid: sort order \"createTime.seconds\" is unsupported"
If i remove the orderBy: 'createTime.seconds' line then the api works but is not ordered as i want. The result is something like that (i abbreviate the json):
{
"jobs": [
{
"labels": {},
"name": "projects/<id>/locations/europe-west1/jobs/<uuid>",
"inputUri": "",
"outputUri": "",
"state": "SUCCEEDED",
"createTime": {
"seconds": "1656602896",
"nanos": 386772728
},
"startTime": {
"seconds": "1656602900",
"nanos": 755000000
},
"endTime": {
"seconds": "1656603062",
"nanos": 428000000
},
"ttlAfterCompletionDays": 30,
"error": null,
"config": {
"inputs": [
{
"key": "input0",
"uri": "gs://<url>/render_md.mp4",
"preprocessingConfig": null
}
],
"editList": [...],
"elementaryStreams": [...],
"muxStreams": [...],
"manifests": [],
"adBreaks": [],
"spriteSheets": [],
"overlays": [],
"output": {
"uri": "gs://<url>/md.mp4/"
},
"pubsubDestination": {
"topic": "projects/<id>/topics/transcoder_api"
}
},
"jobConfig": "config"
},
...
],
"unreachable": [],
"nextPageToken": "Co8BCjgKDGV1cm9wZS13ZXN0MRIZdHJhbnNjb2Rlci5nb29nbGVhcGlzLmNvbRgBII..."
}
As you can see each job have the startTime.seconds property. I follow the syntax described here:
https://google.aip.dev/132#ordering
Any support to solve the ordered issue is appreciated.

Traversing array and changing object values

I'm trying to update the values ​​of my payments array objects
{
"balance": 109610,
"gifts": [],
"orders": [],
"payments": [{
"isPaid": 0,
"status": "Pending",
"address": "3KsdQbmADyz1KNN7qqX1yZcMXBbfFCm31r",
"date": 1624057559970
}, {
"isPaid": 0,
"status": "Pending",
"address": "3FYQK6YiAaL8fEbDWaXYw38CJN3K2y5dPD",
"date": 1624058531601
}],
"isVendedor": false,
"isAdmin": true,
"createdAt": {
"$date": "2021-06-17T21:10:15.020Z"
},
"username": "teste",
"email": "teste#teste.com",
"password": "$2a$10$qUNkorDuvbf.AYLTvjNc4ebKyNgLa7L9NoTBwAIV8.BfN51umaD9O",
"__v": 3
}
First, I look for the object of the user who made a request to my server
const userPayment = await User.find({"payments.address": notification.address}).exec();
Then I go through the user object and find it until I find the position where I find notification.address again
userPayment.forEach((AllPayments, index) => {
AllPayments.payments.forEach((payment, index) => {
if (payment.address == notification.address) {
if (payment.isPaid || payment.status != "Pending")
return res.json({
success: false,
error: "Payment Already Processed!",
});
const valueToDeposit = Math.round(notification.fiat_amount);
console.log(
userPayment[0].payments[index].isPaid,
userPayment[0].payments[index].status
);
// Set payments[index].isPaid = true
// Set payments[index].status = "Paid"
});
});
So I tried to make these 3 ways and none of them was successful.
userPayment[0].balance += valueToDeposit; // this works when save() is triggered
userPayment[0].payments[index].isPaid = 1; // this doesnt works when save() is triggered
userPayment[0].payments[index].status = "Paid"; // this doesnt works when save() is triggered
userPayment[0].updateOne({"payments.address": notification.address}, { $set: { "payments.$.isPaid": 1,"payments.$.status":"Paid" } },(err, result) => { console.log(err, result); }); this doesnt works
userPayment[0].save()

React Native : iterate and display nested objects using Hooks

I want to display my user data stored in my api's
How can I iterate through my apis data.
Can anyone demonstrate it with example ?
My api data looks like this:
{
"data": {
"__v": 0,
"_id": "5edaa8cc76d6b20017",
"createdAt": "2020-06-05T20:19:24.365Z",
"email": "joe#gmail.com",
"name": "Joe",
"role": "user"
},
"success": true
}
Here is the example of my code:
const HomeScreen = props => {
const [dataSource, setDatasource] = useState({});
const Boiler = async () => {
const token = await AsyncStorage.getItem('token');
fetch('{{URL}}/api/v1/auth/me', {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer ' + token,
}),
})
.then(res => res.json())
.then(responeJson => {
console.log(responeJson);
setDatasource({
...dataSource,
dataSource: responeJson,
});
})
.catch(error => {
console.error(error);
});
};
useEffect(() => {
Boiler();
}, []);
}
You response from the API is an object which you can directly render in your component without the need for iteration
Also note that when you update state, you would not explicitly set key as dataSource
Update your state like
setDatasource({
...dataSource,
...responeJson.data,
});
and then render your data like
return (
<View>
<Text>CreatedAt: {dataSource.createdAt}</Text>
<Text>email: {dataSource.email}</Text>
<Text>name: {dataSource.name}</Text>
<Text>role: {dataSource.role}</Text>
</View>
)
If you need to iterate over object use can use for..in loop.
const response = {
"data": {
"__v": 0,
"_id": "5edaa8cc76d6b20017",
"createdAt": "2020-06-05T20:19:24.365Z",
"email": "joe#gmail.com",
"name": "Joe",
"role": "user"
},
"success": true
};
function iterateOverData(data) {
for(let key in data) {
console.log(key, data[key]);
}
}
iterateOverData(response.data);

NodeJS - Elastic Search for insert data to index

I followed this link to get the mapping of the Elastic Search Index and would like to insert data(not include all fields) into it as below, but failed.
Mapping of index:
{
"mymapping": {
"mappings": {
"_meta": {
"beat": "apm",
"version": "7.5.0"
},
"dynamic_templates": [
{
"labels": {
"path_match": "labels.*",
"match_mapping_type": "string",
"mapping": {
"type": "keyword"
}
}
}
],
"properties": {
"#timestamp": {
"type": "date"
},
"people": {
"dynamic": "false",
"properties": {
"id": {
"type": "keyword",
"ignore_above": 1024
},
"name": {
"type": "keyword",
"ignore_above": 1024
}
}
}
}
}
}
}
I prepared client.js without problem, here is InsertData.js:
const esClient = require('./client');
const insertDoc = async function(indexName, _id, mappingType, data){
return await esClient.index({
index: indexName,
type: mappingType,
id: _id,
body: data
});
}
module.exports = insertDoc;
async function test(){
const data = {
beat: 'apm',
version: '7.5.0'
}
try {
const resp = await insertDoc('mymapping', 2, '_meta', data);
console.log(resp);
} catch (e) {
console.log(e);
}
}
test();
When I tried to insert data, there was exception.
Error output:
message:
'[illegal_argument_exception] Rejecting mapping update to [mymapping] as the final mapping would have more than 1 type: [_doc, _meta]',
path: '/mymapping/_doc/2',
query: { type: '_meta' },
body:
{ error:
{ root_cause: [Array],
type: 'illegal_argument_exception',
reason:
'Rejecting mapping update to [mymapping] as the final mapping would have more than 1 type: [_doc, _meta]' },
status: 400 },
statusCode: 400,
response:
'{
"error": {
"root_cause": [
{
"type": "illegal_argument_exception",
"reason": "Rejecting mapping update to [mymapping] as the final mapping would have more than 1 type: [_doc, _meta]"
}
],
"type": "illegal_argument_exception",
"reason": "Rejecting mapping update to [mymapping] as the final mapping would have more than 1 type: [_doc, _meta]"
},
"status": 400
}'
How can insert data properly?
Starting elasticsearch 6+ multiple types have been deprecated. You are trying to explicitly put the type while creating the mapping which is meta and the one which is getting inserted be default is _doc.
See this for more details : Removal of types

How to create a dynamic table with vue js

I have a question. How to create a dynamic table with vue js.
I want to render this json file into the table using Vue but it doesn't happen as I want. I want the data in two languages and app_adi but only the latest data is coming. How can I display both?
json file
{
"accounts":{
"user":{
"_id":"5a500vlflg0aslf011ld0a25a5",
"username":"john",
"id":"59d25992988fsaj19fe31d7",
"name":"Test",
"customer":" John Carew",
},
"application":[
{
"app_id":"5af56pi314-y1i96kdnqs871nih35",
"language":"es"
},
{
"app_id":"5af56pi314-blvinpgn4c95ywyt8j",
"language":"en"
}
]
}
}
I want to build this table:
username customer language app_di
john John Carew es 5af56pi314-y1i96kdnqs871nih35
en 5af56pi314-blvinpgn4c95ywyt8j
Preprocess your json in a computed property.
In your example you just need to add the "user" properties to the first "application" item.
new Vue({
el: '#app',
data() {
return {
columns: {
username: 'Name',
customer: 'Customer',
language: 'Language',
app_id: 'App_ID'
},
userData: {
"user": {
"_id": "5a500vlflg0aslf011ld0a25a5",
"username": "john",
"id": "59d25992988fsaj19fe31d7",
"name": "Test",
"customer": " John Carew",
},
"application": [{
"app_id": "5af56pi314-y1i96kdnqs871nih35",
"language": "es"
},
{
"app_id": "5af56pi314-blvinpgn4c95ywyt8j",
"language": "en"
}
]
}
}
},
computed: {
tableData() {
return this.userData.application.map((x, index) => {
return index === 0 ? Object.assign(x, this.userData.user) : x
})
}
}
})
Here is a working example: https://jsfiddle.net/ellisdod/jm3snwxc/2/

Resources