how to map the data in table row? - node.js

I fetch channels 1,2,3,4 from get method and then call post data in which I call function parameter and check the get method data in the body parameter of post method and print the data of post method but it is in the form of object in the console and I want to store in temp and them display it in the web page.
code*
import React, { useEffect, useState } from "react";
import "./main.css"
import { AiOutlineCheck, AiOutlineClose, AiOutlineArrowUp, AiOutlineArrowDown } from "react-icons/ai";
import axios from "axios";
const Header = () => {
const [setdata, fetchdata] = useState([]);
const [setpostData, Postdata] = useState([]);
useEffect(() => {
getfetchData();
}, [])
useEffect(() => {
setdata.forEach(function (val) {
getPostData(val.Player, val.IP, val.Port, val.ChannelName);
// setInterval(() => {
// getPostData(val.Player, val.IP, val.Port, val.ChannelName);
// }, 500);
});
}, [setdata]);
function getfetchData() {
axios.get("http://localhost:9763/api/getPlayers",
{
headers: {
"accepts": "application/json",
'Access-Control-Allow-Origin': '*',
},
auth: {
username: 'admin',
password: 'password'
},
}).then(response => {
//console.log(response.data)
//console.log([...Object.values(response.data).flat()]);
fetchdata([...Object.values(response.data).flat()]);
}).catch(error => {
console.log(error);
});
}
var temp = [];
// Post Data
function getPostData(Player, IP, Port, channelName) {
var data = {
PlayerName: Player,
ChannelName: channelName,
Port: Port,
IpAddress: IP
}
axios({
method: 'post',
url: 'http://localhost:9763/api/getPlayerStatus',
data,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
auth: {
username: 'admin',
password: 'password'
}
}).then(response => {
}).catch(error => {
console.log("Error In Post Data", error);
});
}
// console.log("set", setpostData);
return (
<div className="container-fluid pt-2">
<table className=" table-borderless text-center" id="refresh">
<thead>
<tr className="title" >
{
Object.values(setdata).map((val) => {
return (
<th key={val.Player} > <AiOutlineCheck style={{ color: 'black', backgroundColor: "#41fc00", borderRadius: "25px" }} />
{val.ChannelName} </th>
)
})
}
</tr>
</thead>
<tbody>
<tr >
{
setpostData.map((val, index) => {
// console.log("Inside Map", val);
return (
<td key={index}>{val.Properties.Upcounter} </td>
)
})
}
</tr>
<tr>
{
setpostData.map((val, index) => {
// console.log("Inside Map", val);
return (
<td key={index}>{val.Properties.DownCounter} </td>
)
})
}
</tr>
</tbody>
</table>
</div >
);
}
export default Header;
Console Response.data show object
how to make this 4 object in one array so that its easily to map in row
[
{
"Status": 1000,
"Properties": {
"ClipName": "Clip1",
"Upcounter": "15:33:44:33",
"DownCounter": "16:33:44:33",
"ChannelName": "Channel1",
"StartTimeCode": "00:00:00:00",
"PlayerName": "Vtr1",
"Duration": "12:00:00:01"
}
}
]
[
{
"Status": 1000,
"Properties": {
"ClipName": "Clip3",
"Upcounter": "12:33:44:33",
"DownCounter": "12:33:44:33",
"ChannelName": "Channel3",
"StartTimeCode": "00:00:00:00",
"PlayerName": "Vtr3",
"Duration": "12:00:00:01"
}
}
]
[
{
"Status": 1000,
"Properties": {
"ClipName": "Clip1",
"Upcounter": "15:33:44:33",
"DownCounter": "16:33:44:33",
"ChannelName": "Channel1",
"StartTimeCode": "00:00:00:00",
"PlayerName": "Vtr1",
"Duration": "12:00:00:01"
}
}
]
[
{
"Status": 1000,
"Properties": {
"ClipName": "Clip1",
"Upcounter": "15:33:44:33",
"DownCounter": "16:33:44:33",
"ChannelName": "Channel1",
"StartTimeCode": "00:00:00:00",
"PlayerName": "Vtr1",
"Duration": "12:00:00:01"
}
}
]

you have to map the values before <tr> I think its work. can you post the output UI of the table
And for merging array object you can do this way. I think its work
var newArray = [...arr1, ...arr2, ...aar3,...arr4];

Related

How to send react native text field value as JSON.stringify

I have code like this:-
export default class TextField extends Component {
constructor(props) {
super(props);
this.state = {
userID: '',
userName: '',
userGmail: '',
userTNumber: '',
};
}
addCustomer = () => {
fetch('http://localhost:3000/send-data', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
});
} <TextInput
style={styles.inputText}
placeholder="User ID :"
placeholderTextColor="#ffff"
onChangeText={userID => this.setState({userID})}
value={this.state.userID}
autoCapitalize="none"
/>
</View>
}
I Need To Send My Text Input To My Node BackEnd...
I Don't Know How To Send My Data Using This Fetch Function
**
addCustomer = () => {
fetch('http://localhost:3000/send-data', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({}),
});
};
**
I Don't Know How To Put My Text Input Into,
body: JSON.stringify({}),
This Is My BackEnd To Post My Data:-
app.post('/send-data', (req, res) => {
const customer = new Customer({
userID: req.body.userID,
userName: req.body.userName,
userGmail: req.body.userGmail,
userTNumber: req.body.userTNumber,
});
customer
.save()
.then(result => {
console.log(result);
res.send(result);
})
.catch(err => {
console.log(err);
});
});
Can You Help Me ..?
ThankYou..!
If I understood correctly, you want to pass your data in the following format:
{
"userID": 1,
"userName": "John Doe",
"userGmail": "john.doe#example.com",
"userTNumber": "1234"
}
You want to use the data from your state and pass it to the fetch function, like so:
export default class TextField extends Component {
constructor(props) {
super(props)
this.state = {
userID: "",
userName: "",
userGmail: "",
userTNumber: "",
}
}
addCustomer = () => {
const { userID, userName, userGmail, userTNumber } = this.state
fetch("http://localhost:3000/send-data", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ userID, userName, userGmail, userTNumber }),
})
}
render() {
return (
<TextInput
style={styles.inputText}
placeholder="User ID :"
placeholderTextColor="#ffff"
onChangeText={(userID) => this.setState({ userID })}
value={this.state.userID}
autoCapitalize="none"
/>
)
}
}

Angular Get Data From JSON to Model And List It

I'm trying to get data from a JSON using Angular and map it to a model, then show it on a webpage.
I did it buy I'm not getting any results, like the data from JSON cannot be taken or something.
Here's my try:
The JSON:
{
"location": [
{
"_id": "5f3567a8d8e66b41d4bdfe5f",
"lat": "44.4363228",
"lng": "25.9912305",
"token": "edb153fb9d8d5628",
"__v": 0
}
]
The model:
export class Post {
public _id: string;
public token: string;
public lat: string;
public lng: string;
}
Service class:
#Injectable({ providedIn: 'root' })
export class PostsService {
public posts: Post[] = [];
private postsUpdated = new Subject<Post[]>();
Post: Promise<any>;
constructor(private http: HttpClient) {}
private url: string = 'http://localhost:8000/location';
getPosts() {
this.http
.get<{ posts: any[] }>(this.url)
.pipe(
map((postData) => {
return postData.posts.map((post) => {
console.log(this.posts);
return {
_id: post._id,
token: post.token,
lat: post.lat,
lng: post.lng,
};
});
})
)
.subscribe((transformedPosts) => {
this.posts = transformedPosts;
this.postsUpdated.next([...this.posts]);
});
}
getPostUpdateListener() {
return this.postsUpdated.asObservable();
}
}
post-list.component.ts:
#Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls: ['./post-list.component.css'],
})
export class PostListComponent implements OnInit, OnDestroy {
posts: Post[] = [];
private postsSub: Subscription;
result: any;
constructor(public postsService: PostsService) {
//dependency-injection
}
ngOnInit() {
this.postsService.getPosts();
this.postsSub = this.postsService
.getPostUpdateListener()
.subscribe((posts: Post[]) => {
this.posts = posts;
});
}
onShow() {
console.log('TODO');
}
ngOnDestroy() {
this.postsSub.unsubscribe();
}
}
post-list.component.html:
<mat-accordion multi="true" *ngIf="posts.length > 0">
<mat-expansion-panel *ngFor="let post of posts">
<mat-expansion-panel-header>
{{ post.token }}
</mat-expansion-panel-header>
<p>{{ post.lat }}</p>
<p>{{ post.lng }}</p>
<mat-action-row>
<button mat-raised-button color="accent" (click)="onShow(post._id)">
SHOW
</button>
</mat-action-row>
</mat-expansion-panel>
</mat-accordion>
<p class="info-text mat-body-1" *ngIf="posts.length <= 0">No posts added yet</p>
app.component.html:
<app-header></app-header> <br /><br />
<agm-map [latitude]="lat" [longitude]="lng" [zoom]="zoom">
<agm-marker [latitude]="lat" [longitude]="lng"></agm-marker>
</agm-map>
<br /><br />
<app-post-list></app-post-list>
And here's my result (photo):
I also tried to do it in different ways, always getting no result.
Any help or ideas would be much appreciated!
The error in the image says posts attribute does not exists on postData object which is gotten by get request. Absence of posts attribute is also clear in the JSON you provided.
{
"location": [
{
"_id": "5f3567a8d8e66b41d4bdfe5f",
"lat": "44.4363228",
"lng": "25.9912305",
"token": "edb153fb9d8d5628",
"__v": 0
}
]
You should completely remove the pipe and it should be fine.

Render JSON with sub object using React

Maybe someone there knows, how can I render "department" object from JSON?
[
{
"id": 1,
"name": "one",
"department": {
"id": 1,
"name": "development"
}
},
{
"id": 2,
"name": "two",
"department": {
"id": 2,
"name": "testing"
}
}
]
I am trying to display the data such that It's my render
render() {
const title =<h3>Employee</h3>;
const {Employees, isLoading} = this.state;
if (isLoading)
return(<div>Loading....</div>);
let rows=
Employees.map( employee =>
<tr key={employee.id}>
<td>{employee.id}</td>
<td>{employee.name}</td>
<td>{employee.department.name}</td>
<td><Button size="sm" color="danger" onClick={() => this.remove(employee.id)}>Delete</Button></td>
</tr>);
return {rows};
Tanx very much!
render() {
const title =<h3>Employee</h3>;
const {Employees, isLoading} = this.state;
if (isLoading)
return(<div>Loading....</div>);
let rows=
Employees.map( employee => {
return `<tr key=${employee.id}>
<td>${employee.id}</td>
<td>${employee.name}</td>
<td>${employee.department.name}</td>
<td><Button size="sm" color="danger" onClick=${() => this.remove(employee.id)}>Delete</Button></td>
</tr>` });
return {rows};
I fixed id! I needed to my back end code modify some... from "department" to private String departmentName;
and front
let rows=
Employees.map( employee =>
<tr key={employee.id}>
<td>{employee.id}</td>
<td>{employee.name}</td>
<td>{employee.department.departmentName}</td>
<td><Button size="sm" color="danger" onClick={() => this.remove(employee.id)}>Delete</Button></td>
</tr>);

Vuetify v-data-table search.filter not showing any results

Getting data back from our API but built in Vuetify search/filter is not working. I think it has to do with the data coming back being nested in an object. When typing in the search filter i get "No matching records found" after the first character, when removing the search term the full data table is displayed. Thanks in advance for any help.
<template>
<v-container
fill-height
fluid
grid-list-xl
>
<v-layout
justify-center
wrap
>
<v-flex
md6
>
<material-card
color="black"
title="Users"
>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Search"
single-line
hide-details
></v-text-field>
<v-data-table
:headers="headers"
:items="userData"
:search="search"
hide-actions
>
<template
slot="headerCell"
slot-scope="{ header }"
>
<span
class="subheading font-weight-light text-dark text--darken-3"
v-text="header.text"
/>
</template>
<template
slot="items"
slot-scope="{ item }"
>
<td>
<v-avatar slot="offset" class="mx-auto d-block" size="100">
<img v-if="item.ProfileImage==null" src="img/conectrlogo.jpg">
<img v-else v-bind:src= "item.ProfileImage">
</v-avatar></td>
<td><v-btn text-small outlined color="primary" #click= "goToUserProfile(item.Id)">{{ item.Id}}</v-btn></td>
<td>{{ item.Username}}</td>
<td>{{ item.Name}}</td>
</template>
</v-data-table>
</material-card>
</v-flex>
</v-layout>
</v-container>
</template>
Script
<script>
import axios from 'axios'
export default {
mounted()
{
console.log("got into mounted function");
this.getResults();
},
data () {
return {
customFilter: function (items, search, filter, headers) {
search = search.toString().toLowerCase()
if (search.trim() === '') return items
const props = headers.map(h => h.value)
return items.filter(item => props.some(prop => filter(getObjectValueByPath(item, prop, item[prop]), search)))
},
userData:[],
totalUsers:0,
showResults:true,
search:'',
headers:[
{
text: 'User',
value: 'profileimage',
align: 'center',
width: '50px',
sortable:false
},
{
text: 'id',
value: 'id',
align: 'center',
width: '100px',
sortable:false
},
{
text: 'Username', value: 'username',
align: 'left',
sortable: false,
width: '50px'
},
{
text: 'Name', value: 'name',
align: 'left',
sortable: true,
width: '50px'
}
]
}
},
computed:{
},
methods: {
goToUserProfile: function(Id)
{
console.log("avatar clicked:"+Id);
this.$router.push('/user-profile/'+Id)
},
getResults (){
console.log("got into the all users endpoint");
console.log(this.$baseUrl+'/admin/users');
// axios.get(this.$baseUrl+'/admin/users',
// {withCredentials: true}).then ( response => {
// this.userData=response.data.Users;
// this.totalUsers = response.data.UserCount;
// console.log("all user response:"+this.userData);
// });
//this.showResults=true;
axios.defaults.withCredentials = true;
axios(this.$baseUrl+'/admin/users', {
method: 'GET',
withCredentials: true,
crossDomain:true
}).then(res => {
console.log(res);
this.userData=res.data.Users;
this.totalUsers = res.data.UserCount;
console.log("all user response:"+this.userData);
}).catch(err => {
console.log("got an error");
console.log(err);
})
},
initialize()
{
},
}
}
</script>

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

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

Resources