I am creating a sample fullstack application in angular to do CRUD operations on employee data such as image, name, email, phone, salary and department. I am using kendo grid to show, add and edit employee data. I am using Node JS for API and Mongo DB for database.
I am able to view the employee data and add new employees to list. But i am unable to edit the details using kendo grid. I do not know how to pass value from kendo grid to .ts file.
Below is the code i am working on.
I don't know how to pass the data or update it by employee id. I have used event method but it didn't work. I tried passing dataItem through button click method as well, but it doesn't work
Help me on this.
employee-list.component.html
<form novalidate #myForm="ngForm">
<kendo-grid
[kendoGridTemplateEditing]="createNewEmployee"
[kendoGridBinding]="employees"
[pageSize]="5"
[pageable]="true"
[sortable]="true"
[navigable]="true">
<ng-template kendoGridToolbarTemplate>
<button kendoGridAddCommand type="button">Add new</button>
</ng-template>
<kendo-grid-column title="Profile Picture" [style]="{'text-align': 'center'}" [width]="200">
<ng-template kendoGridCellTemplate let-dataItem>
<img src={{dataItem.imageData}}
onerror=" this.src = './../../assets/placeholder.png' "
height="100" width="100" style="border-radius:50px;" alt="Employee Image"/>
</ng-template>
<ng-template kendoGridEditTemplate let-dataItem="dataItem">
<ng-container *ngIf="imageUrl;else elseTemplate">
<img [src]="dataItem.imageData ? dataItem.imageData : imageUrl" height="100" width="100" style="border-radius:50px;" />
</ng-container>
<ng-template #elseTemplate>
<img src="./../../assets/placeholder.png" height="100" width="100" style="border-radius:50px;">
</ng-template>
<input kendoGridFocusable class="form-control my-2" type="file" id="profileImage" accept="image/*" (change)="onFileChange($event)" required>
</ng-template>
</kendo-grid-column>
<kendo-grid-column field="_id" title="id">
<ng-template kendoGridEditTemplate let-dataItem>
<input
[(ngModel)]="dataItem._id"
kendoGridFocusable
name="ID"
class="k-textbox k-input k-rounded-md"
required
/>
</ng-template>
</kendo-grid-column>
<kendo-grid-column field="name" title="Name">
<ng-template kendoGridEditTemplate let-dataItem>
<input
[(ngModel)]="dataItem.name"
kendoGridFocusable
name="name"
class="k-textbox k-input k-rounded-md"
required
/>
</ng-template>
</kendo-grid-column>
<kendo-grid-column field="email" title="Email">
<ng-template kendoGridEditTemplate let-dataItem>
<input
[(ngModel)]="dataItem.email"
kendoGridFocusable
name="email"
class="k-textbox k-input k-rounded-md"
/>
</ng-template>
</kendo-grid-column>
<kendo-grid-column field="phone" editor="numeric" title="Phone">
<ng-template kendoGridEditTemplate let-dataItem>
<input
[(ngModel)]="dataItem.phone"
kendoGridFocusable
name="phone"
type="number"
/>
</ng-template>
</kendo-grid-column>
<kendo-grid-column field="salary" editor="numeric" title="Salary">
<ng-template kendoGridEditTemplate let-dataItem>
<input
[(ngModel)]="dataItem.salary"
kendoGridFocusable
name="salary"
required
class="k-textbox k-input k-rounded-md"
type="number"
/>
</ng-template>
</kendo-grid-column>
<kendo-grid-column field="department" title="Department">
<ng-template kendoGridEditTemplate let-dataItem="dataItem">
<input
[(ngModel)]="dataItem.department"
kendoGridFocusable
name="department"
required
class="k-textbox k-input k-rounded-md"
/>
</ng-template>
</kendo-grid-column>
<kendo-grid-command-column title="command" [width]="220">
<ng-template kendoGridCellTemplate let-isNew="isNew">
<button kendoGridEditCommand type="button" [primary]="true">
Edit
</button>
<button kendoGridRemoveCommand type="button">Remove</button>
<ng-container *ngIf="isNew; else update">
<button kendoGridSaveCommand [disabled]="!myForm.valid" (click)="addEmployee()">Add</button>
</ng-container>
<ng-template #update>
<button kendoGridSaveCommand [disabled]="!myForm.valid" (click)="updateEmployee()">Update</button>
</ng-template>
<button kendoGridCancelCommand type="button">
{{ isNew ? "Discard changes" : "Cancel" }}
</button>
</ng-template>
</kendo-grid-command-column>
</kendo-grid>
</form>
employee-list.component.ts
export class EmployeesListComponent implements OnInit{
employees: Employee[] = [];
baseApiUrl: string = environment.baseApiUrl;
image: File = null;
imageUrl: string;
employeeDetails: Employee = {
_id: '',
name: '',
email: '',
phone: 0,
salary: 0,
department: '',
imageData: '',
selected: false
};
constructor(
private employeesService: EmployeesService,
private router: Router,
private httpClient: HttpClient
) {}
ngOnInit(): void {
this.employeesService.getAllEmployees().subscribe(
dataEmployees => this.employees = dataEmployees
);
}
onFileChange(event){
this.image = event.target.files[0];
const reader = new FileReader();
reader.readAsDataURL(this.image);
reader.onload = () => {
this.imageUrl = reader.result as string;
};
}
createNewEmployee(): Employee {
return new Employee()
}
addEmployee(){
this.employeesService.addEmployee(this.employees[0], this.image).then(
(response) => {
this.router.navigate(['']);
console.log(this.employees[0].department);
},
(error) => {
console.log(error);
}
);
}
updateEmployee(){
this.employeesService.updateEmployee(this.employeeDetails._id, this.employeeDetails, this.image).then(
(response) => {
this.router.navigate(['']);
},
(error) => {
console.log(error);
}
);
console.log("employee edit")
}
}
I am using employeeDetails to store the updated data and pass it on to service but the updated details aren't stored in it
employee.service.ts
export class EmployeesService {
baseApiUrl: string = environment.baseApiUrl;
constructor(private http: HttpClient) { }
getAllEmployees(): Observable<Employee[]>{
return this.http.get<Employee[]>(this.baseApiUrl + '/employees');
}
updateEmployee(id: string, updateEmployeeRequest: Employee, image:File){
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
if(image != null){
fileReader.readAsDataURL(image);
fileReader.onload = () => {
updateEmployeeRequest.imageData = fileReader.result as string;
this.http.patch(this.baseApiUrl + '/employees/' + id, updateEmployeeRequest).subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
}
}
else {
this.http.patch(this.baseApiUrl + '/employees/' + id, updateEmployeeRequest).subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
}
});
}
}
Related
I have a form that is working to send emails from a contact form on Next.js using API routes and I'm trying to add attachments to the form. The form sends the email with everything including the attachment but the attachment is broken. I've read every question on here relating to it and it's still not working.
My guess is it's the
const attachments = Buffer.from(body.attachments).toString("base64");
causing the issue. Probably not converting correctly. I have limited experience with Buffer.
//email form for invidual van magazine inquiries
const sgMail = require("#sendgrid/mail");
sgMail.setApiKey(process.env.SENDGRID_API_KEY_LETTER);
export default async function handler(req, res) {
const body = JSON.parse(req.body);
console.log(body.attachments);
const attachments = Buffer.from(body.attachments).toString("base64");
const msg = \`
Name: ${body.name}\\r\\n
Phone: ${body.phone}\\r\\n
Email: \<a href="mailto:${body.email}"\>${body.email}\</a\>\\r\\n
Letter: ${body.letter}
\`;
const data = {
to: "john#doe.com",
from: `info#randomcompany.com`,
subject: `${body.subject}`,
text: msg,
html: msg.replace(/\\r\\n/g, "\<br /\>"),
attachments: [
{
content: attachments,
filename: "attachment.pdf",
type: "application/pdf",
disposition: "attachment",
},
],
};
await sgMail
.send(data)
.then(() =\> {
console.log("Email sent");
})
.catch((error) =\> {
console.log(error.response.body);
});
res.status(200).json({ status: "ok" });
}
The form on the frontend is :
<motion.form
initial={{ opacity: 0, y: 100 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 1.0 }}
onSubmit={handleSubmit}
className="mt-16 flex flex-col lg:flex-row rounded-l-lg justify-center items-center"
>
<div className="flex flex-col space-y-3 justify-center items-center">
<input
id="name"
name="name"
type="text"
className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-sm sm:mx-2 focus:ring-none focus:outline-none w-[350px] "
placeholder="Name"
required
/>
<input
id="subject"
name="subject"
type="text"
className="hidden"
disabled
value={`Letter to the Editor`}
/>
<input
id="email"
name="email"
type="text"
className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-sm sm:mx-2 focus:ring-none focus:outline-none w-[350px]"
placeholder="Email Address"
required
/>
<input
id="phone"
type="text"
name="phone"
className="px-4 py-2 text-gray-700 bg-white border border-gray-300 rounded-sm sm:mx-2 focus:ring-none focus:outline-none w-[350px]"
placeholder="Phone (optional)"
/>
<textarea
name="letter"
id="letter"
className="px-4 h-48 py-2 text-gray-700 bg-white border border-gray-300 rounded-sm sm:mx-2 focus:ring-none flex justify-center items-center focus:outline-none w-[350px]"
placeholder="Letter To The Editor"
></textarea>
<div className="flex flex-col text-center items-center justify-center text-sm w-3/4 ">
<label
className="flex justify-center items-center w-full mx-4 my-5"
htmlFor="attachments"
>
Attach PDF?
</label>
<input
className="flex justify-center items-center w-full mx-auto my-2"
type="file"
name="attachments"
id="attachments"
/>
</div>
const handleSubmit = async (e) => {
e.preventDefault();
const formData = {};
Array.from(e.currentTarget.elements).forEach((field) => {
if (!field.name) return;
formData[field.name] = field.value;
});
fetch("/api/letter", {
method: "POST",
body: JSON.stringify(formData),
});
// }).then(() => {
// setSubmitted(true);
// });
};
If anyone can point me in the correct direction it would be greatly appreciated
I have tried using setting the state with the file but that didn't work
Here is the console log that returns after sending the email
console.log("body:", req.body);
const body = JSON.parse(req.body);
console.log("body attachments:", body.attachments);
const attachments = Buffer.from(body.attachments).toString("base64");
console.log("attachments:", attachments);
body: {"name":"Chris","subject":"Letter to the Editor","email":"asada#ada.com","phone":"test","letter":"test","attachments":"C:\\fakepath\\upwork js questions.pdf"}
body attachments: C:\fakepath\upwork js questions.pdf
attachments: QzpcZmFrZXBhdGhcdXB3b3JrIGpzIHF1ZXN0aW9ucy5wZGY=
Email sent
I have a two test suites. One actually makes API calls, and seems to run in about 20 seconds. Other one, is literally empty and takes over 248 seconds. Two of the tests are todo, and one had some implementation that I commented out. It's still taking forever. Why is this?
import { render, waitFor, screen } from "#testing-library/react";
import MyContent from "./MyContent.js";
describe('MyContent Component', () => {
it.todo('should call API when search button is clicked');
it('should render some text when api responds', () => {
/*
render(<MyContent />);
await waitFor(() => {
screen.getByText("some text");
});
*/
});
it.todo('should render error message when api fails');
});
Here is my jest config defined inside package.json
"jest": {
"transform": {
"^.+\\.[t|j]sx?$": "babel-jest"
},
"testEnvironment": "jsdom"
},
I need to use jsdom because there is a window.location in existing code.
Update: Adding component code
import React, { useState } from "react";
import { Input } from "#progress/kendo-react-inputs";
import { Label } from "#progress/kendo-react-labels";
import * as Constants from "../common/Constants.js";
import SearchTextBox from "../../components/SearchTextbox/SearchTextbox.js";
import someService from "../../services/someService.js";
import { Update } from "#material-ui/icons";
function MyContent(props) {
const isThatPage = props.pageIdentifier == Constants.PageIdentifier.thatPage;
const [eDetailsOutput, seteDetailsOutput] = useState({
a: null,
b: null,
c: null,
d: null
});
const handleChange = (e) => {
let dataToPush = [];
dataToPush.push({ key: e.target.name, value: e.target.value });
if (props.handleChange) {
props.handleChange(dataToPush);
}
};
const thatInput = {
q: null,
w: null,
eId: null,
x: null,
z: props.z
};
const handleSearchClick = () => {
someService.getthatDetailsBya(thatInput)
.then((response) => {
let updatedValue = {};
updatedValue = {
a: response?.eDetails.a,
b: response?.eDetails.b,
c: response?.eDetails.c,
d: response?.eDetails.d
}
seteDetailsOutput(eDetailsOutput => ({
...eDetailsOutput,
...updatedValue
}));
})
.catch((error) => {
goToAPIErrorPage(error?.message);
});
};
return (
<div className="k-form form_margin">
<div className="k-geo-form">
<div className="card">
<div className="card-item">
<div className="row">
<div className="col-lg-4 col-md-4 col-sm-4 col-xs-4 form-group">
<Label>el Name</Label>
{isThatPage ? (
<SearchTextBox
id="z-textbox"
name="z"
value={props.z ?? ""}
handleChange={handleChange}
readOnly={props.isReadOnly}
handleSearchClick={handleSearchClick}
/>
) : (
<Input
id="z-textbox"
name="z"
value={props.z ?? ""}
onChange={handleChange}
className={props.isReadOnly ? "readOnlyInput" : ""}
readonly={props.isReadOnly}
/>
)}
</div>
<div className="col-lg-4 col-md-4 col-sm-4 col-xs-4 form-group">
<Label>a</Label>
{isThatPage ? (
<SearchTextBox
id="a-textbox"
name="a"
// value={props.a ?? ""}
value={eDetailsOutput.a ?? "aIII"}
handleChange={handleChange}
readOnly={props.isReadOnly}
handleSearchClick={handleSearchClick}
/>
) : (
<Input
id="a-textbox"
name="a"
value={props.a ?? ""}
onChange={handleChange}
className={props.isReadOnly ? "readOnlyInput" : ""}
readonly={props.isReadOnly}
/>
)}
</div>
<div className="col-lg-4 col-md-4 col-sm-4 col-xs-4 form-group">
<Label>Entity Category Type</Label>
<Input
id="b-textbox"
name="b"
// value={props.b ?? ""}
value={eDetailsOutput.b ?? "beee"}
onChange={handleChange}
className={props.isReadOnly ? "readOnlyInput" : ""}
readonly={props.isReadOnly}
/>
</div>
</div>
<div className="row">
<div className="col-lg-4 col-md-4 col-sm-4 col-xs-4 form-group">
<Label>Status</Label>
<Input
id="Status-textbox"
name="Status"
// value={props.Status ?? ""}
value={eDetailsOutput.c ?? "csssss"}
onChange={handleChange}
className={props.isReadOnly ? "readOnlyInput" : ""}
readonly={props.isReadOnly}
/>
</div>
<div className="col-lg-4 col-md-4 col-sm-4 col-xs-4 form-group">
<Label>Other Status</Label>
<Input
id="OtherStatus-textbox"
name="OtherStatus"
value={props.OtherStatus ?? ""}
onChange={handleChange}
className={props.isReadOnly ? "readOnlyInput" : ""}
readonly={props.isReadOnly}
/>
</div>
<div className="col-lg-4 col-md-4 col-sm-4 col-xs-4 form-group">
<Label>Some Role</Label>
<Input
id="Role-textbox"
name="Role"
value={props.Role ?? ""}
onChange={handleChange}
className={props.isReadOnly ? "readOnlyInput" : ""}
readonly={props.isReadOnly}
/>
</div>
</div>
<div className="row">
<div className="col-lg-4 col-md-4 col-sm-4 col-xs-4 form-group">
<Label>Some Type</Label>
<Input
id="Type-textbox"
name="Type"
value={eDetailsOutput.d ?? "deeeeee"}
onChange={handleChange}
className={props.isReadOnly ? "readOnlyInput" : ""}
readonly={props.isReadOnly}
/>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
export default MyContent;
I have a form which has a input field called admissionNumber and the button. In input field when user enter number and click the button then function getAllStudent filter the an array . If admission number match with entered number then other fields (fullname and faculty) automatically filled . How can I do this ? Please someone help me to do this . Thank you
getAllStudents function which return students details (admissionNumber,fullname,faculty)
getAllStudents(user._id, token).then((data) => {
if (data.error) {
setValues({ ...values, error: data.error });
} else {
setValues(data);
}
});
form fields
<input
type="text"
onChange={(event) => {
setSearchTerm(event.target.value);
}}
className="form-control offset-md-2 col-md-6"
placeholder="Admission Number"
required
maxLength="5"
/>
<button
// onClick={}
className="btn rounded ml-4"
>
Verify
</button>
</div>
<div className="bg-dark rounded">Personal Details</div>
<div className="row form-group ">
<input
type="text"
name="studentFullName"
className="form-control mt-2 offset-md-2 col-md-8"
placeholder="Student Name"
/>
<input
type="text"
name="faculty"
className="form-control mt-2 offset-md-2 col-md-8"
/>
</div>
You should pass a function to button onClick prop.
Assuming you using a functional component and a state with students, currentUser and searchTerm you can do something like that:
const [students] = useState([...])
const [currentUser, setCurrentUser] = useState(undefined)
const [searchTerm, setSearchTerm] = useState(undefined)
const checkStudent = () => {
const match = students.find(student => student.admissionNumber === searchTerm)
if(match) {
setCurrentUser(match)
}
}
return (
<>
<button
onClick={() => checkStudent()}
/>
<input
type="text"
name="studentFullName"
className="form-control mt-2 offset-md-2 col-md-8"
placeholder="Student Name"
value={currentUser?.fullname}
/>
</>
)
I try to upload a photo from React and save it in a public folder on the backend and then display the filename in the MySql database
After trying it through Postman, the photo has been successfully uploaded and appears and produces a json like this
{"image":"/img/14d714a9ed97fb92db657b9518e89a1e.png",
"id_produk":23,
"id_user":19,
"Nama_toko":"Nihongo Mantappu",
"Nama_Produk":"Butter",
"Deskripsi":"Mentega Blueband 50g",
"Price":5000,
"Jumlah_stock":7},
but when I tried it in React it only produced this
{"image":"/img/",
"id_produk":29,
"id_user":19,
"Nama_toko":"Nihongo Mantappu",
"Nama_Produk":"Beras Cinajur",
"Deskripsi":"Beras Cianjur 1kg",
"Price":500000,"Jumlah_stock":20}
so that when i check the database on the image it becomes empty
here the code for upload image
import React from 'react'
import jwt_decode from 'jwt-decode';
import 'bootstrap/dist/css/bootstrap.min.css';
import NavbarPenjual from '../../Component/NavbarPenjual';
import {addproduk} from '../../View/UserFunctions';
import { Form,Col, Button } from 'react-bootstrap';
class TambahProduk extends React.Component{
constructor(){
super()
this.state={
id_user:'',
Nama_toko:'',
Nama_produk: '',
Harga:'',
image: '',
Deskripsi: '',
Jumlah_produk: '',
error:{}
}
this.onChange=this.onChange.bind(this)
this.onSubmit=this.onSubmit.bind(this)
}
onChange(e){
this.setState({[e.target.name]:e.target.value})
}
componentDidMount(){
const token = localStorage.getItem('usertoken')
const decoded= token ? jwt_decode(token) : null;
this.setState({
id_user:decoded.id_user,
Nama_toko:decoded.Nama_toko
})
}
onSubmit(e){
e.preventDefault()
const newProduk={
id_user:this.state.id_user,
Nama_toko:this.state.Nama_toko,
Nama_Produk: this.state.Nama_Produk,
Price:this.state.Price,
image: this.state.image,
Deskripsi: this.state.Deskripsi,
Jumlah_stock: this.state.Jumlah_stock,
}
console.log(newProduk)
addproduk(newProduk).then(res =>{
//localStorage.setItem('usertoken',res.data.token);
this.props.history.push(`/DashboardPenjual`)
}).catch(err=>{
console.log(err)
alert("gagal")
})
}
render(){
return(
<div>
<NavbarPenjual/>
<Form className="container"style={{marginTop:28}} noValidate onSubmit={this.onSubmit}>
<h2>Tambah Produk</h2>
<Form.Row controlId="exampleForm.ControlInput1">
<Form.Label column lg={2}>
Nama Produk
</Form.Label>
<br/>
<Col>
<Form.Control
type="text"
placeholder="Masukan Nama Produk"
name="Nama_Produk"
value={this.state.Nama_Produk}
onChange={this.onChange}
/>
</Col>
</Form.Row>
<br/>
<Form.Row controlId="exampleForm.ControlInput1">
<Form.Label column lg={2}>
Harga Produk
</Form.Label>
<br/>
<Col>
<Form.Control type="text"
placeholder="Masukan Harga Produk"
name="Price"
value={this.state.Price}
onChange={this.onChange}
/>
</Col>
</Form.Row>
<br/>
<Form.Row controlId="exampleForm.ControlInput1">
<Form.Label column lg={2}>
Jumlah Produk
</Form.Label>
<br/>
<Col>
<Form.Control
type="text"
placeholder="Masukan Jumlah Produk"
name="Jumlah_stock"
value={this.state.Jumlah_stock}
onChange={this.onChange}
/>
</Col>
</Form.Row>
<br/>
<Form.Row controlId="exampleForm.ControlInput1">
<Col>
<Form.Group controlId="exampleForm.ControlTextarea1">
<Form.Label>Deskripsi Produk</Form.Label>
<br/>
<Form.Control
as="textarea"
rows="3"
name="Deskripsi"
value={this.state.Deskripsi}
onChange={this.onChange}
/>
</Form.Group>
</Col>
</Form.Row>
<br/>
<Form.Row controlId="exampleForm.ControlInput1">
<Form.Group>
<Form.File
id="exampleFormControlFile1"
label="Masukan Foto Produk"
type="image"
name="image"
value={this.state.image}
onChange={this.onChange}
/>
</Form.Group>
</Form.Row>
<br/>
<button
type="submit"
className="btn btn-lg btn-primary btn-block"
>Submit</button>
<Form.Row controlId="exampleForm.ControlInput1" style={{ visibility: "hidden" }}>
<Col>
<Form.Group controlId="exampleForm.ControlInput1">
<br/>
<Form.Control
as="text"
name="id_user"
value={this.state.id_user}
onChange={this.onChange}
/>
</Form.Group>
</Col>
</Form.Row>
<Form.Row controlId="exampleForm.ControlInput1" style={{ visibility: "hidden" }}>
<Col>
<Form.Group controlId="exampleForm.ControlTextarea1">
<br/>
<Form.Control disabled
as="area"
name="Nama_toko"
value={this.state.Nama_toko}
onChange={this.onChange}
/>
</Form.Group>
</Col>
</Form.Row>
</Form>
</div>
)
}
}
export default TambahProduk;
this is part of the axios userfuction for add product
export const addproduk = newProduk =>{
return axios
.post('product/addproduk',{
id_user:newProduk.id_user,
Nama_toko:newProduk.Nama_toko,
Nama_Produk:newProduk.Nama_Produk,
image: newProduk.image,
Deskripsi:newProduk.Deskripsi,
Price:newProduk.Price,
Jumlah_stock:newProduk.Jumlah_stock
})
.then(res=>{
console.log("produk di tambahkan")
return res
})
.catch(err=>{
console.log(err);
return err;
})
}
How do I get uploaded like when I use Postman?
Image is not an value, it's a file. So, in the onChange function you assigned the image.target.name as value
Try like this :
event.target.name === "image"? event.target.files[0] : event.target.value;
I'm using bootrap-table from http://bootstrap-table.wenzhixin.net.cn/.
I'm using reactjs to render the table after searching for data, the problem is although the table have data on it, it's still showing that "no matching
records found". Please help me, thank you.
This is my react code for render table:
import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
class Form extends React.Component {
render() {
return (
<form onSubmit={this.props.submitData}>
<h2 className="card-inside-title">Floating Label Examples</h2>
<div className="row clearfix">
<div className="col-sm-12">
<div className="form-group form-float form-group-lg">
<div className="form-line">
<input type="text" className="form-control" name="stockNumber" autoFocus
onChange={this.props.inputChange}/>
<label className="form-label">Stock number</label>
</div>
</div>
<div className="form-group form-float form-group-lg">
<div className="form-line">
<input type="text" className="form-control" name="personalPassportId"
onChange={this.props.inputChange}/>
<label className="form-label">Personal ID/Passport number</label>
</div>
</div>
<div className="form-group form-float form-group-lg">
<div className="form-line">
<input type="text" className="form-control" name="name"
onChange={this.props.inputChange}/>
<label className="form-label">Stockholder name</label>
</div>
</div>
</div>
</div>
<div className="row clearfix">
<div className="col-sm-12">
<button type="submit" className="btn btn-lg btn-primary waves-effect">
Submit
</button>
</div>
</div>
</form>
)
}
}
class Rows extends React.Component {
render() {
return (
<tr>
<td>{this.props.rowData.stocknumber}</td>
<td>{this.props.rowData.personalpassportid}</td>
<td>{this.props.rowData.name}</td>
</tr>
)
}
}
class Table extends React.Component {
constructor(props) {
super(props);
this.state = {
rowsData: []
};
}
componentWillReceiveProps(nextProps) {
this.setState({
rowsData: nextProps.tableData
});
}
render() {
var rows = [];
this.state.rowsData.forEach((rowsData) => {
rows.push(<Rows rowData={rowsData} key={rowsData.id}/>)
});
return (
<table data-toggle="table">
<thead className="bg-deep-orange">
<tr>
<th>Stock Number</th>
<th>Personal/Passport ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
)
}
}
class Content extends React.Component {
constructor(props) {
super(props);
this.state = {
stockNumber: '',
personalPassportId: '',
name: '',
tableData: null
};
this.inputChange = this.inputChange.bind(this);
this.submitData = this.submitData.bind(this)
};
inputChange(event) {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
};
submitData(event) {
const {stockNumber, personalPassportId, name} = this.state;
axios.post('/attend', {
stockNumber: stockNumber,
personalPassportId: personalPassportId,
name: name
}).then((response) => {
this.setState({
tableData: response.data
});
}).catch((err) => {
console.log(err);
});
event.preventDefault();
};
render() {
return (
<div>
<Form inputChange={this.inputChange} submitData={this.submitData}/>
<div className="row clearfix">
<div className="col-sm-12">
<Table tableData={this.state.tableData}/>
</div>
</div>
</div>
)
}
}
ReactDOM.render(<Content/>, document.getElementById('content'));
Table keep showing "No matching records found"