Map array dont show in table - node.js

I need map a array inside my page, and show the result in a table, but the content don't show up when I compiled the page.
Can anyone help me?
When I print in console the content of a var, this is here. But the info don't show up in the page
import Layout, { siteTitle } from '../components/layout'
const fetch = require('node-fetch');
export default function Home({ devices }) {
return (
<Layout >
{devices.map((device) => (
<table>
<thead>
<th>
{device.localname} / {device.localIP}
</th>
</thead>
{console.log('1')}
<tbody>
<tr>
<td>
{device.IPaddress[0][3].value} // I put this to test, and this works fine
</td>
</tr>
{device.IPaddress.map((port) =>{
<tr>
<td>
{console.log(port[3].value), port[3].value} // here I need to work, I want to put all results of port in a TD tag, the console.log shows up the info, but the page not.
</td>
</tr>
})}
</tbody>
</table>
))}
</Layout >
)
}
export async function getStaticProps() {
const res = await fetch('http://localhost:3000')
const devices = await res.json()
return {
props: {
devices
}
}
}

As commented by #evgenifotia, change the ( for { inside the second array map works fine.
here the final function:
export default function Home({ devices }) {
return (
<Layout >
{devices.map((device) => (
<table>
{console.log('1')}
<tbody>
<tr>
<th>
{device.localname} / {device.localIP}
</th>
</tr>
{device.IPaddress.map(port =>(
<tr>
<td>
{console.log(port[3].value), port[3].value}
</td>
</tr>
))}
</tbody>
</table>
))}
</Layout >
)
}

Related

Uncaught IntegrationError: Invalid stripe.redirectToCheckout parameter: items.0.price is not an accepted parameter

My goal is to use react front end to setup a stripe checkout using node. I mapped the apiId using the key prop to iterate over all the items in my list. But there is an integration warning inside the console and I'm not sure why. I've added the js.stripe script src into my html file so I don't understand why an API call is not being made.
function checkout() {
stripe.redirectToCheckout({
items: items.map(item => ({
quantity: item.quantity,
price: item.apiId
})),
successUrl: "https://www.website.com/success",
cancelUrl: "https://www.website.com/canceled",
})
}
return (
<div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Image</th>
<th>Quanity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{items.map((item) => (
<tr key={item.apiId}>
<td>{item.name}</td>
<td>
<img
src={`/images/${item.apiId}.jpg`}
alt={item.name}
width={180}
/>
</td>
<td>{item.quantity}</td>
<td>{formatPrice(item.price)}</td>
</tr>
))}
<tr>
<td style={{ textAlign: "right" }} colSpan={3}>
Total:
</td>
<td>{formatPrice(totalPrice(items))}</td>
</tr>
<tr>
<td style={{ textAlign: "right" }} colSpan={4}>
<button onClick={checkout}>Complete checkout</button>
</td>
</tr>
</tbody>
</table>
</div>
)
}
The items field only accepts an array of SKU/Plans and a quantity. If you're using Prices you want to use lineItems: https://stripe.com/docs/js/checkout/redirect_to_checkout#stripe_checkout_redirect_to_checkout-options-lineItems

NodeJS template literal with async map

I'm trying to generate an HTML content using template literal because I need to loop through an array. It is not returning the map content to the template literal.
const htmlData = `
<html>
... // Some content here
<table class="table table-bordered" style="width: 800px;" align="center">
<thead class="thead-light">
<tr>
<th>Company</th>
<th>Bill Date</th>
<th>Billing Days</th>
<th>Total Units</th>
</tr>
</thead>
<tbody>
${customers.map( async (customer) => {
let units = 0;
const companyDate = new Date(customer.CompanyStartDate);
const billDate = new Date(today.getFullYear(), today.getMonth(), companyDate.getDate());
const numDays = (today.getTime() - billDate.getTime()) / (1000 * 3600 * 24);
const pData = await property.getPropTotalUnitsByCompany(customer.CompanyID);
return (
`
<tr>
<td>
${pData.map(async (propData) => {
units += propData.TotalUnits;
return (
`
<div class="row">
<div class="col-sm-12" align="right">
Property: ${propData.PropertyName} Total Units: ${propData.TotalUnits}
</div>
</div>
`
);
})}
</td>
<td>${myFunctions.formatDisplayDate(billDate)}</td>
<td>${numDays}</td>
<td>${units}</td>
</tr>
`
);
})}
</tbody>
</table>
... // More content here
</html>
`;
It returns [object Promise] inside my . Here is where I have the .map(). Can't I use map in template literals?
Thank you

How to call a delete function with parameter(_id) outside the class in react js?

This is what I have tried? I wanted to call the deleteDebt() function in the code. But I can't pass the function to const Debt. (Outside the class) How can I do that?
Here I want to pass the props.debt._id through the function. Because I want to delete the particular row in the table with it's _id.
const Debt = props => (
<tr>
<td>{props.debt.fullName}</td>
<td>{props.debt.damount}</td>
<td>
<button className="btn btn-danger btn-info " type="delete" onClick={() => this.deleteDebtor(props.debt._id)}>DELETE</button>
</td>
</tr>
)
export default class profile extends Component {
constructor(props) {
super(props);
this.deleteDebtor = this.deleteDebtor.bind(this);
this.state = {
fullName: '',
damount: '',
users: []
}
}
this is where i get data from the database.
componentDidMount() {
axios.get('url')
.then(response => {
this.setState({ users: response.data.data });
})
.catch(function (error) {
console.log(error);
})
}
this is where i make the table.
UserList() {
// console.log(this.state.users);
return this.state.users.map(function (currentDebt, i) {
return <Debt debt={currentDebt} key={i} />;
}
}
this is the deleteDebt() function.
deleteDebtor(data) {
axios.delete('url' + data)
}
this is rendering part
render() {
return (
<React.Fragment>
<div >
<table } >
<thead>
<tr>
<th>Name </th>
<th>Amount</th>
</tr>
</thead>
<tbody>
{this.UserList()}
</tbody>
</table>
</div>
</React.Fragment>
)
}
}
You can pass a reference to the this.deleteDebtor as props.
<Debt delete={this.deleteDebtor} debt={currentDebt} key={i} />;
const Debt = props => (
<tr>
<td>{props.debt.fullName}</td>
<td>{props.debt.damount}</td>
<td>
<button className="btn btn-danger btn-info " type="delete" onClick={() => props.delete(props.debt._id)}>DELETE</button>
</td>
</tr>
)
Note that this will re-render the component whenever the parent re-renders because a new function gets created on each render.
You can use React.memo to prevent that:
const Debt = React.memo(props => (
<tr>
<td>{props.debt.fullName}</td>
<td>{props.debt.damount}</td>
<td>
<button className="btn btn-danger btn-info " type="delete" onClick={() => props.delete(props.debt._id)}>DELETE</button>
</td>
</tr>
));
update
I think you have a scoping issue change the normal function inside map into an arrow function:
UserList() {
// console.log(this.state.users);
return this.state.users.map((currentDebt, i) => {
return <Debt delete={this.deleteDebtor} debt={currentDebt} key={i} />;
});
}

How to use search filter in Angular for nested JSON object?

I am bringing data from my mongoose to display on my HTML table. I am able to filter a JSON object normally but unable to filter nested JSON object?
I have used "npm i ng2-search-filter --save " to import filter pipe, but this only works for the first level. Doesn't do filter for the nested JSON object.
My JSON object is:
{
packageName:test,
packagePrice:200,
userid:{
userName:John,
userAge: 27
}
}
<input type="text" class="form-control" [(ngModel)]="searchtext"
placeholder="Search">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Package Name</th>
<th scope="col">Package Price</th>
<th scope="col">Customer Name</th>
<th scope="col">Customer Age</th>
</tr>
</thead>
<tbody *ngFor="let use of user | filter:searchtext">
<tr class="table-active">
<td> {{use.packageName}}</td>
<td>{{use.packagePrice}}</td>
<td>{{use.userid.userName}}</td>
<td>{{use.userid.userAge}}</td>
</tr>
</tbody>
</table>
When I enter packageName and packagPrice in a textbox for search filter it filters out and shows me correct result, but on userName and userAge its not working.
Please help.
Thank you.
I solved this with by just installing the latest version ng2 search filter.
Run below command:
npm i ng2-search-filter#0.5.1
You can use custom search pipe for this
I have create demo on Stackblitz
searchPipe.ts
transform(value: any, searchText?: any): any {
if(!value) return [];
if(!searchText) return value;
searchText = searchText.toLowerCase();
return value.filter( it => {
return it.packageName.toLowerCase().includes(searchText) || it.packagePrice.toString().includes(searchText) || (it.userid && it.userid.userAge.toString().includes(searchText) || it.userid.userName.toLowerCase().includes(searchText));
});
}
component.html
<tr class="table-active" *ngFor="let use of user | search:searchtext">
<td> {{use.packageName}}</td>
<td>{{use.packagePrice}}</td>
<td>{{use.userid.userName}}</td>
<td>{{use.userid.userAge}}</td>
</tr>
Try the below:-
function getResult(filterBy, objList) {
return objList.hightlights.filter(function(obj) {
return obj.queries.some(function(item){
return item.indexOf(filterBy) >= 0;
});
});
}

How can i render data on change?

I'm trying to build a project in nodejs as server and firebase as my realtime db and having some problems with forwarding the data to my html.
I getting the error:
Cannot set headers after they are sent to the client
on change
I'm trying to pass the updated arr to html but can't find a way to do that.
server.js:
const locksRef = await firebase.firebase.database().ref('locks')
let arr = []
//get list of locks
const t = locksRef.on('value', (data) => {
tempResult3 = data.val()
result3 = []
const numOfKeys = Object.keys(tempResult3)
numOfKeys.forEach((x) => {
result3.push(tempResult3[x])
})
result3.forEach((k) => {
myLocks.forEach((my) => {
if (k.id == my) {
arr.push(k)
}
})
})
res.render('ListOfLocks', { arr })
})
html
<body>
<h1>ListOfHouses</h1>
<table border="1px solid black">
<thead>
<th>Name And Address</th>
</thead>
<tbody>
{{#each arr}}
<tr>
<td id="data"> {{name}} - {{address}}</td>
<td>
<form action="/seekKeys" method="post"><button name="{{locks}}" type="submit">LookForKey</button>
</form>
</td>
</tr>
{{/each}}
</tbody>
</table>
</body>

Resources