Datatable server side processing in react js - node.js

I tried to add jquery datatable in react with server side processing. I'm new to react so, i can't find any better module to implement this. I tried following code its not returning any error but, data not loading into table even data retrieved correctly from endpoint.
import React, {Component} from 'react';
import '../assets/css/datatable.css';
const $ = require('jquery');
$.DataTable = require('datatables.net');
class Table extends Component {
componentDidMount() {
$(this.refs.main).DataTable({
dom: '<"#example">',
processing: true,
language: {
"processing": 'Loading...'
},
serverSide: true,
ajax: {
url: 'http://localhost:5001/endpoint',
type: 'post',
dataSrc: ""
},
columns: [
{ "title": "value", "name":"value", "data": "value", "className":"link text-left text-nowrap" },
{ "title": "created_at", "name":"createdAt", "data": "createdAt", "className":"link text-left text-nowrap", "visible": false, "searchable": false}
]
});
}
render() {
return (
<div>
<table ref="main" />
</div>);
}
}
export default Table;
Please, help me to resolve this issue. Thank you in advance.

My API response like below.
{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
[
"Airi",
"Satou",
"Accountant",
"Tokyo",
"28th Nov 08",
"$162,700"
],
[
"Angelica",
"Ramos",
"Chief Executive Officer (CEO)",
"London",
"9th Oct 09",
"$1,200,000"
]
]
}
So I add ajax.dataSrc: 'data' this in datatable options. It's working good & datas are loaded.
I think dataSrc is your problem

Related

Microsoft Teams task module with URL not working for external url

trigger a task module that will display a web page. All I was able to get is an empty Task Module with the title, while the specified height and width do not showing URL displayed.
i want to redirect the url from the api.,but api is giving a url but not redirecting
let requestUrl = await getRedirectUrlForSubmitAction(tokenResponse) ===> api call to get the url
const response: MessagingExtensionActionResponse = <MessagingExtensionActionResponse>{
task: {
type: "continue",
value: {
title: "Send recognition",
url: `${request.data.value}`, //url from api call
height: "large"
}
}
};
return Promise.resolve(response);
please check this below code for external url redirecting
<html>
<head>
<title>Redirecting</title>
<script src='https://statics.teams.cdn.office.net/sdk/v1.6.0/js/MicrosoftTeams.min.js'></script>
</head>
<body>
<div id='app'>
<header style="display: flex; justify-content: center;align-items: center; font-size: 1rem;">
<h1>Redirecting <em>....</em></h1>
</header>
</div>
<script type="text/javascript">
function login() {
microsoftTeams.initialize();
if (window.location.href.includes("redirectUrl.action")) {
let token = localStorage.getItem("appToken");
let urlStr = window.location.href.split('?url=')[1]
fetch(`${urlStr}`, {
method: 'GET',
headers: new Headers({
"content-type": "application/json",
"originated": "teams",
"post-type": "ajax",
"outlookauth": `${token}`
}),
})
.then(res => res.json())
.then(
(result) => {
console.log("result", result);
location.href = result.url
//return result.url
},
(error) => {
console.log("Error", error);
}
)
} else {
//balance
const host = window.location.href.split('&host=')[1].split('&')[0]
const appcode = window.location.href.split('&appCode=')[1]
const token = localStorage.getItem("appToken");
const urlType = window.location.href.split('?url=')[1]
const urlStr = `https://${host}/${appcode}/mobileapp/teams/teamsShopRedirectUrl.action?${urlType}`
fetch(`${urlStr}`, {
method: 'GET',
headers: new Headers({
"content-type": "application/json",
"originated": "teams",
"post-type": "ajax",
"outlookauth": `${token}`
}),
})
.then(res => res.json())
.then(
(result) => {
window.location.href = result.url
},
(error) => {
console.log("Error", error);
}
)
}
}
window.onload = login();
</script>
</body>
</html>
manifest file
{
"$schema": "https://developer.microsoft.com/en-us/json-schemas/teams/v1.8/MicrosoftTeams.schema.json",
"manifestVersion": "1.8",
"id": "{{APPLICATION_ID}}",
"version": "{{VERSION}}",
"packageName": "{{PACKAGE_NAME}}",
"developer": {
"name": "name",
"websiteUrl": "https://{{HOSTNAME}}/now",
"privacyUrl": "https://{{HOSTNAME}}/now/privacy.html",
"termsOfUseUrl": "https://{{HOSTNAME}}/now/tou.html"
},
"name": {
"short": "Now",
"full": "Now"
},
"description": {
"short": "for Teams",
"full": "."
},
"icons": {
"outline": "icon-outline.png",
"color": "icon-color.png"
},
"accentColor": "#FFFFFF",
"configurableTabs": [],
"staticTabs": [],
"bots": [
{
"botId": "{{MICROSOFT_APP_ID}}",
"needsChannelSelector": true,
"isNotificationOnly": false,
"scopes": [
"team",
"personal",
"groupchat"
],
"commandLists": [
{
"scopes": [
"team",
"personal"
],
"commands": [
{
"title": "test1",
"description": "test1"
},
{
"title": "test2",
"description": "test2 "
}
]
}
],
"supportsFiles": true,
"supportsCalling": true,
"supportsVideo": true
}
],
"connectors": [],
"composeExtensions": [
{
"botId": "{{MICROSOFT_APP_ID}}",
"canUpdateConfiguration": true,
"messageHandlers": [
{
"type": "link",
"value": {
"domains": [
"{{HOSTNAME}}",
"avidanpprd.performnet.com",
"youtube.com"
]
}
}
],
"commands": [
{
"id": "MessageExtension",
"title": "title",
"description": "Add a clever description here",
"initialRun": true,
"type": "action",
"context": [
"compose"
],
"fetchTask": true
}
]
}
],
"permissions": [
"identity",
"messageTeamMembers"
],
"validDomains": [
"{{HOSTNAME}}",
"avidanpprd.performnet.com",
"youtube.com"
],
"showLoadingIndicator": true,
"isFullScreen": false
}
This is probably a combination of things:
You need to make sure that the website you're showing is listed as a 'safe' domain in your manifest for your Teams app. I think you need something in both the messageHandlers > value > domain section as well as the validDomains section in the root level of the manifest.
However, depending on what you're trying to embed, it might not work because the external site has to have some basic Teams integration. See this heading, where it says:
For your page to display in Teams, you must include the Microsoft Teams JavaScript client SDK and include a call to microsoftTeams.initialize() after your page loads.
As a result, if this is an external site you don't control, you might need to have your own page that you host in the task module, which simpyly iframes in the external website.
This issue might come if the URL doesn't support iframe embedding.
To help you here you can refer the sample and try to bind the URL in iframe like below in your page.
<iframe width="700" height="700" src="https://www.example.com/embed/QPSaLnaU" allow="autoplay; encrypted-media"></iframe>
I have been recently working on something similar.
I have a message extension (build using Adaptive cards) and on one of the button clicks, I want to trigger Upload Document functionality. Unfortunately, an adaptive card doesn't provide.
So, I build an separate angular web-page, which will act as an upload application.
Note: The domain of the webpage should be added correctly under validDomains in the manifest file.
"validDomains": [
"*.example.com",
],
On button click in message extension (NodeJS):
...
return {
task: {
type: 'continue',
value: {
height: 400,
width: 400,
title: 'Task module WebView',
url: `https://show.example.com`
}
}
};
For more info visit:
Upload attachment from messages extension in MS Teams

find by category in array object not working in Angular frontend

I'm trying to build a blog application using Angular on frontend with node, express in the backend and mongodb as database. Now I'm trying to make a component called blog-categories where there should be a method to iterate the whole database and search by the key category and return the values in the component such that all the category values are now shown in the component and when someone will click the values all blogs having such categories will get displayed. In case if you want to have a better look at the project you can check out my git repository https://github.com/tridibc2/blog-admin-mean . But it seems that the route is not able to catch the category. In the header it is going null. localhost:4000/api/v1/blogs/view/by/category/null The typical database looks somewhat like this:
{
"error": false,
"message": "All Blogs found Successfully",
"status": 200,
"data": [
{
"title": "Blog Title 2 Custom edited",
"description": "Blog description 2 Custom Edited",
"bodyHtml": "<h3>Heading of the body CUSTOM</h3><p>This is the first blog data getting uploaded n blog project</p>\nedited",
"views": 9,
"isPublished": true,
"category": "Comedy",
"author": "Decardo",
"tags": [
"english movies, action movies, comedy"
],
"blogId": "nbfO8hJp",
"created": "2020-01-04T23:33:38.000Z",
"lastModified": "2020-01-04T23:33:38.000Z"
},
{
"title": "Blog Title 2",
"description": "Blog description 2",
"bodyHtml": "",
"views": 1,
"isPublished": true,
"category": "tech",
"author": "Xtremator",
"tags": [
"english movies",
" action movies",
" comedy"
],
"blogId": "ZW8OR7vc",
"created": "2020-01-04T23:34:08.000Z",
"lastModified": "2020-01-04T23:34:08.000Z"
}
]
}
blog-category.component.ts
import { Component, OnInit } from '#angular/core';
import { BlogpostService } from '../blogpost.service';
import { Router, ActivatedRoute} from '#angular/router';
#Component({
selector: 'app-blog-category',
templateUrl: './blog-category.component.html',
styleUrls: ['./blog-category.component.css']
})
export class BlogCategoryComponent implements OnInit {
public categories;
constructor(private blogpostService: BlogpostService, private route: ActivatedRoute,
private router: Router) { }
ngOnInit() {
let myBlogcatrgory = this.route.snapshot.paramMap.get('category');
this.blogpostService.viewByCategory(myBlogcatrgory).subscribe(
data =>{
console.log(data);
this.categories = data["category"];
},
error =>{
console.log("some error occured");
console.log(error.errorMessage);
}
);
}
}
blog-category.component.html
<h3>Categories</h3>
<ul>
<li *ngFor="let category of categories">
{{category.name}}
</li>
</ul>
</div>

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

Having issues using axios to handle my JSON data

I am trying to setState from this data,
var axios = require('axios');
import Trails from './trails';
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
trails: []
}
}
componentWillMount() {
axios
.get('https://www.mtbproject.com/data/get-trails-by-id?ids=2081068,830442%208013961&key=(API-KEY)')
.then(response => response.data)
.then(trails => this.setState({trails}));
}
which looks like this:
{
"trails": [
{
"id": 2081068,
"name": "San Dieguito River Park - Bernardo Bay\/ Piedras Pintadas Trail",
"type": "Featured Ride",
"summary": "Sweet little loop of singletrack trails.",
"difficulty": "blue",
"stars": 3.6,
"starVotes": 24,
"location": "Escondido, California",
"url": "https:\/\/www.mtbproject.com\/trail\/2081068\/san-dieguito-river-park-bernardo-bay-piedras-pintadas-trail",
"imgSqSmall": "https:\/\/cdn-files.apstatic.com\/mtb\/2148715_sqsmall_1372258680.jpg",
"imgSmall": "https:\/\/cdn-files.apstatic.com\/mtb\/2148715_small_1372258680.jpg",
"imgSmallMed": "https:\/\/cdn-files.apstatic.com\/mtb\/2148715_smallMed_1372258680.jpg",
"imgMedium": "https:\/\/cdn-files.apstatic.com\/mtb\/2148715_medium_1372258680.jpg",
"length": 8.2,
"ascent": 570,
"descent": -567,
"high": 488,
"low": 317,
"longitude": -117.0766,
"latitude": 33.0512,
"conditionStatus": "All Clear",
"conditionDetails": "Dry",
"conditionDate": "2018-09-11 09:12:17"
}
],
"success": 1
}
Then I am trying to map it like this:
render() {
return (
<div className='App'>
<div className="container">
<div className="jumbotron">
<h4>Mtb</h4>
<p>Trails:</p>
</div>
{this.state.trails.map(trail => (
<Trails key={trail.id}
conditions={trail.conditionDetails}
/>
))
}
</div>
</div>
);
}
}
I then get an error saying that my map method is not a function. Can someone point out what I am doing wrong?
When I console.log my state it appears that it is not being set, might this be the issue and be the explanation for why it is not working?
You are setting trails to be the entire data object you get in response to your request. Use the trails property of the data object instead.
componentWillMount() {
axios
.get('https://www.mtbproject.com/data/get-trails-by-id?ids=2081068,830442%208013961&key=(API-KEY)')
.then(response => this.setState({ trails: response.data.trails }));
}

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