Error occurs in the template of component EmployeeCreateComponent - node.js

I'm new to Angular and working on httpclient and httpservice project of CRUD application. While compiling with ng serve in VS code I get the following error:
error: ERROR in src/app/employee-create/employee-create.component.html:18:65 - error TS2554: Expected 1 arguments, but got 0.
employee-create.component.html
<div class="container custom-container">
<div class="col-md-12">
<h3 class="mb-3 text-center">Create Employee</h3>
<div class="form-group">
<input type="text" [(ngModel)]="employeeDetails.name" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="text" [(ngModel)]="employeeDetails.email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="text" [(ngModel)]="employeeDetails.phone" class="form-control" placeholder="Phone">
</div>
<div class="form-group">
<button class="btn btn-success btn-lg btn-block" (click)="addEmployee()">Create Employee</button>
</div>
</div>
</div>
employee-create component.ts
import { Component, OnInit, Input } from '#angular/core';
import { Router } from '#angular/router';
import { RestApiService } from "../shared/rest-api.service";
#Component({
selector: 'app-employee-create',
templateUrl: './employee-create.component.html',
styleUrls: ['./employee-create.component.css']
})
export class EmployeeCreateComponent implements OnInit {
#Input() employeeDetails = { name: '', email: '', phone: 0 }
constructor(
public restApi: RestApiService,
public router: Router
) { }
ngOnInit() { }
addEmployee() {
this.restApi.createEmployee(this.employeeDetails).subscribe((data: {}) => {
this.router.navigate(['/employees-list'])
})
}
}

The error is obvious in your template addEmployee() method on button click doesnt have any param.
(click)="addEmployee()"
But in your component you are passing dataEmployee param in addEmployee(dataEmployee) method (which looks like not in use).
Hence you can remove dataEmployee param from addEmployee() method.
addEmployee() { // <=== no dataEmployee param
this.restApi.createEmployee(this.employeeDetails).subscribe((data: {}) => {
this.router.navigate(['/employees-list'])
})
}

addEmployee() { // <=== dataEmployee Parameter this.restApi.createEmployee(this.employeeDetails).subscribe((data: {}) => {
this.router.navigate(['/employees-list'])
})
}
you are not passing a Parameter in Html file but you are trying to get parameter in ts that's why you are getting Error.

Related

Force preact-router to reload a page completely

I have a page that contains a link to a secondary page that creates a record. Here is the problem I'm running into: If I fill out the fields on the secondary page, and return back to create another item, the previous data is still inside my text boxes.
I don't know if this is just how preact works. I thought that by calling route it would unmount the component, thus clearing state. I even tried adding unique keys to my routes (which I heard forces them to unmount).
I really am at wits end.
app.jsx
const App = () => (
<div>
<Header/>
<Router history={createHashHistory()}>
<Home path="/" />
<DisplayUsers key="displayUsers" path="/display-users"/>
<CreateUser key="createUser" path="/create-user"/>
</Router>
</div>
);
create-item.jsx
import { h, Component } from "preact";
import { route } from 'preact-router';
import { $post } from "app/services/ajax.jsx";
import Section from "app/components/section/section.jsx";
import UserList from "app/components/user-list/user-list.jsx";
class CreateUser extends Component {
constructor(props) {
super(props);
this.state = {
userName: "",
route: ""
};
}
handleSubmit = (event) => {
event.preventDefault();
$post("/api/users", this.state, () =>
{
route('/display-users');
}
);
}
handleChange = (event) => {
this.setState({
[event.target.name]: event.target.value
});
}
render() {
return (
<Section title="New User">
<form onSubmit={this.handleSubmit}>
<div className="mat-field">
<label
htmlFor="userName"
className="mat-field__label">
User Name:
</label>
<input
type="text"
id="userName"
name="userName"
className="mat-field__input"
autoComplete="off"
autoFocus="autoFocus"
maxlength="30"
required
onChange={this.handleChange}/>
</div>
<div className="mat-field">
<label
htmlFor="route"
className="mat-field__label">
Route To:
</label>
<UserList
name="route"
onChange={this.handleChange}/>
</div>
{/* Buttons */ }
<div>
<input
type="submit"
value="Create"
className="mat-button mat-button--secondary mat-button--raised"/>
<a
href="/display-users"
className="mat-button">Cancel</a>
</div>
</form>
</Section>
);
}
}
export default CreateUser;

Angular 5 Select multiple returns selected object instead of array with selected object

I have this very annoying problem. Let me add my html:
<div class="page">
<h1>Add user</h1>
<form [formGroup]="inviteUserForm" (ngSubmit)="onSubmit()" novalidate>
<div class="row">
<div class="form-group col-lg-6">
<label for="email">
Email
</label>
<input class="form-control" id="email" formControlName="email">
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="roles">
User role
</label>
<select class="form-control" id="roles" multiple formControlName="roles">
<ng-container *ngFor="let role of roles">
<option *ngIf="role !== 5" value="{{role}}">{{role | userRole}}</option>
</ng-container>
</select>
</div>
</div>
<div class="row">
<div class="form-group col-lg-6">
<label for="account">
Account
</label>
<select class="form-control" id="accounts" multiple formControlName="accounts">
<ng-container *ngFor="let account of accounts">
<option [attr.selected]="activeAccount.id == account.id"
value="account">{{account.name}}</option>
</ng-container>
</select>
</div>
</div>
<button class="btn btn-primary" type="submit">Invite user</button>
</form>
And the controller code:
import {Component} from '#angular/core';
import {FormBuilder, FormGroup, Validators} from '#angular/forms';
import {Router} from "#angular/router";
import {ErrorService} from '../../../../_services/error.service';
import {UserService} from '../../../../_services/user.service';
import {AccountService} from '../../../../_services/account.service';
import {Account} from '../../../../_models/account';
import {UserType} from '../../../../_enums/user-type.enum';
#Component({
selector: 'user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent {
inviteUserForm: FormGroup;
userType: UserType;
accounts: Account[];
activeAccount: Account;
roles: number[];
constructor(private errorService:ErrorService,
private formBuilder: FormBuilder,
private userService: UserService,
private accountService: AccountService,
private router: Router) {}
ngOnInit() {
this.inviteUserForm = this.formBuilder.group({
email: ["", [Validators.required, Validators.email]],
accounts: [[], [Validators.required]],
roles: [[], [Validators.required]]
});
this.accountService.getAccounts().subscribe(
(accounts) => {
this.accounts = accounts;
this.activeAccount = this.accountService.getActiveAccount(this.accounts);
this.inviteUserForm.controls['accounts'].setValue(this.activeAccount);
}
);
this.roles = this.getUserRoles();
}
onSubmit() {
if (this.inviteUserForm.valid){
this.userService.invite(this.inviteUserForm.value).subscribe(
() => this.router.navigate(['/settings/users']),
(error) => this.errorService.setError(error)
);
}
}
getUserRoles(): Array<number> {
var keys = Object.keys(UserType);
return keys.slice(0, keys.length / 2).map(item => parseInt(item));
}
}
My problem is that when I select the account and submit it, it is sent as an object instead of an array. See submitted json from this code here.
{
"email":"test#test.com",
"accounts":{
"id":1,
"name":"Test business",
"addressLine1":"A road",
"addressLine2":"Centrum",
"postalCode":"12345Z",
"postalCity":"London",
"country":"Great Britain",
"type":"business",
"vatNumber":"123456123456"
},
"roles":["3"]
}
At the moment I have only one account in the accounts array.
Any suggestions on how to fix this? I am totally clueless as to why it returns the object from the form.value call instead of the array with the object in it.
I will add an answer to my own question. The problem is in the setValue call. I should have added an array with the selected object instead of just the selected object. I will leave this in here just for information if someone else does the same mistake.

how to update a login name in header component from logincomponent in angularjs 4.0

Hi I need to update login name in a header after a user logs in.
this is my code:
app.componet.html
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
app.component.ts
import { Component,OnDestroy } from '#angular/core';
import { MyservicesService } from './myservices.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
constructor(private myservices: MyservicesService) {
}
}
Header.component.html
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img class="img-responsive" src="assets/images/logo.png" alt="logo">
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li><a routerLink="home" routerLinkActive="active">Home</a></li>
<li><a routerLink="shop">Shop</a></li>
<li>About us</li>
<li>Contact</li>
<li *ngIf="displayuser" class="dropdown">
<a class="dropdown-toggle displaycurrentuser" data-toggle="dropdown" href="#">{{currentusername}}
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a (click)="logOut()">Log out</a></li>
</ul>
</li>
<li *ngIf="!displayuser"><button style="margin-top: -10px;" class="btn btn-primary"> Login / Register</button></li>
<li><a routerLink="cartlist"><span><i class="fa fa-shopping-cart" aria-hidden="true"></i> {{noofitemsincart}} </span></a></li>
</ul>
</div>
</div>
</nav>
Header.component.ts
import { Component, OnInit,Input } from '#angular/core';
import { AuthenticationService } from '../authentication.service';
import { MyservicesService } from '../myservices.service';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
displayuser:boolean = false;
currentusername;
noofitemsincart;
user:any;
constructor(private authenticationService: AuthenticationService,private myservices: MyservicesService) {
}
ngOnInit() {
this.user = this.authenticationService.getCurrentUserData();
if(this.user!=null){
//this.user=JSON.parse(this.user);
if(this.user.UserNameorEmail!=null){
this.displayuser=true;
console.log("displayuser "+this.displayuser);
this.currentusername=this.user.UserNameorEmail;
}
}
}
logOut() {
this.user= this.authenticationService.logout();
this.displayuser=false;
}
}
Loginorregistercomponent.html
<section class="news_area newsblock">
<div class="container">
<div class="row">
<div class="section-title">
<h2>my <span>account</span></h2>
</div>
</div>
<!--endrow-->
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-12 spaceblock">
<div class="login">
<h3 class="titlel">Login</h3>
</div>
<form name="form" (ngSubmit)="loginform.form.valid && login()" #loginform="ngForm" novalidate>
<div class="loginpart">
<div class="form-group froma" [ngClass]="{'has-error': loginform.submitted && !username.valid}">
<label for="email">Username or email address <span class="required"> *</span></label>
<input type="email" class="form-control" id="email" placeholder="" name="username" name="username" [(ngModel)]="model.username"
#username="ngModel" required>
<div *ngIf="loginform.submitted && !username.valid" class="help-block">Username is required</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': loginform.submitted && !password.valid }">
<label for="pwd">Password<span class="required"> *</span></label>
<input type="password" class="form-control" id="pwd" placeholder="" name="password" [(ngModel)]="model.password" #password="ngModel"
required>
<div *ngIf="loginform.submitted && !password.valid" class="help-block">Password is required</div>
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<button [disabled]="lloading" type="submit" class="btn btn-primary">Login</button>
<img *ngIf="lloading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=="
/>
<div class="lostpass">Lost your password?</div>
<div *ngIf="lerror" class="danger">{{lerror}}</div>
</div>
</form>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 spaceblock">
<div class="login">
<h3 class="titlel">Register</h3>
</div>
<form name="form" (ngSubmit)="registerform.form.valid && register()" #registerform="ngForm" novalidate>
<div class="loginpart">
<div class="form-group froma" [ngClass]="{ 'has-error': registerform.submitted && !newusername.valid }">
<label for="email">Email address <span class="required"> *</span></label>
<input type="email" class="form-control" id="email" placeholder="" name="newusername" [(ngModel)]="registermodel.newusername"
#newusername="ngModel" required>
<div *ngIf="registerform.submitted && !newusername.valid" class="help-block">Username is required</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': registerform.submitted && !newpassword.valid }">
<label for="pwd">Password<span class="required"> *</span></label>
<input type="password" class="form-control" id="pwd" placeholder="" name="newpassword" [(ngModel)]="registermodel.newpassword"
#newpassword="ngModel" required>
<div *ngIf="registerform.submitted && !newpassword.valid" class="help-block">Password is required</div>
</div>
<button type="submit" [disabled]="rloading" class="btn btn-primary">Register</button>
<img *ngIf="rloading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=="
/>
<div *ngIf="rerror" class="danger">{{rerror}}</div>
</div>
</form>
</div>
</div>
<!--endimgSection-->
</div>
</section>
Loginorregistercomponent.ts
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { AuthenticationService } from '../authentication.service';
#Component({
selector: 'app-loginorregister',
templateUrl: './loginorregister.component.html',
styleUrls: ['./loginorregister.component.css']
})
export class LoginorregisterComponent implements OnInit {
model: any = {};
registermodel: any = {};
lloading = false;
rloading = false;
returnUrl: string;
lerror;
rerror;
constructor( private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService) { }
ngOnInit() {
this.authenticationService.logout();
// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
login() {
        this.lloading = true;
        this.authenticationService.login(this.model.username, this.model.password)
            .subscribe(
                data => {
console.log(data);
if(!data.hasOwnProperty('Code')){
this.router.navigate([this.returnUrl]);
}else{
this.lerror=data.Message;
console.log(this.lerror);
                    this.lloading = false;
}
                
                },
                error => {
                    //this.alertService.error(error);
this.lerror=error;
console.log(error);
                    this.lloading = false;
                });
    
    }
register() {
this.rloading = true;
this.authenticationService.create(this.registermodel.newusername, this.registermodel.newpassword)
.subscribe(
data => {
data=JSON.parse(data);
if(!data.hasOwnProperty("Code")){
this.router.navigate([this.returnUrl]);
console.log("in data "+data);
}
else{
console.log("out data "+data.Message);
this.rerror=data.Message;
this.rloading = false;
}
},
error => {
// this.alertService.error(error);
this.rerror=error;
this.rloading = false;
});
}
}
authenticationService.ts
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
#Injectable()
export class AuthenticationService {
user:any;
headers = new Headers({ 'Content-Type': 'application/json' });
options = new RequestOptions({ headers: this.headers });
constructor(private http: Http) { }
login(username: string, password: string) {
return this.http.post('http://www.myweb.com/User/Login', JSON.stringify({UserNameorEmail: username,Password: password}),this.options)
.map((response: Response) => {
let user = response.json();
console.log("in service "+user);
if (user) {
localStorage.setItem('currentUser', JSON.stringify(user));
console.log("user.token "+user);
}
return user;
});
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
}
create(username: string, password: string) {
return this.http.post('http://www.myweb.com/User/Add', JSON.stringify({UserNameorEmail: username, Password: password }),this.options)
.map((response: Response) => {
let user = response.json();
if (user) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
return user;
});
}
getCurrentUserData(){
this.user= localStorage.getItem("currentUser");
this.user=JSON.parse(this.user);
if(this.user!=null){
if(this.user.UserNameorEmail!=null){
return this.user;
}else{
return this.user=null;
}
}else{
return this.user=null;
}
}
}
I typically have a state.service.ts in my projects in which I store application state (current user etc.)
In this, I create the following:
// BehaviorSubject to store UserName
private currentUserNameStore = new BehaviorSubject<string>("");
// Make UserName store Observable
public currentUserName$ = this.currentUserNameStore.asObservable();
// Setter to update UserName
setCurrentUserName(userName: string) {
this.currentUserNameStore.next(userName);
}
Then in the header component where you need to display the current User, you subscribe to the Observable from your state service:
stateSvc.currentUserName$
.subscribe(
userName => {
userName = userName;
});
And you can display this in the header like this:
{{userName}}
Then in your login component, once you've got a logged in user, you set the value using the Setter in the service:
this.stateSvc.setCurrentUserName(this.userName);
As the Title on the header component is subscribed, it will pickup the changes and update the display on the component.
You have to check authenticity of user before loading <app-header> </app-header>
i.e.
<div *ngIf="authorised">
<app-header></app-header>
</div>
where authorised is a member of app.component.ts.
i.e. You have to make sure if displayuser or currentusername is available before rendering <app-header></app-header>.
Please mark if you find it helpful.

render table via reactjs keep showing no matching records found

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"

ReduxForm handleSubmit refreshes page with fields assigned

Environment
ReduxForm: v6.5.0
Node: v8.1.2
Browser: Google Chrome
I've gone through all the existing issues on handleSubmit page refreshing, but none of them seems to solve my problem.
LoginForm
import React, { Component } from 'react'
import { reduxForm, Field, propTypes } from 'redux-form'
import classNames from 'classnames'
import loginValidation from './validation'
#reduxForm({
form: 'loginForm',
validate: loginValidation
})
export default class LoginForm extends Component {
static propTypes = {
...propTypes
}
inputField = ({ input, label, type, meta: { touched, error } }) => (
<fieldset className="form__fieldset login-form__fieldset">
<div className="form__field">
<input {...input}
type={type}
placeholder={touched && error ? error : label}
className={classNames('form__input login-form__input',
touched && error ? 'ng-invalid' : ''
)}
/> {/* .ng-invalid */}
</div>
{type === 'password' &&
<div className="form__helper login-form__helper">
<div className="small">
<a>I've forgotten my password</a>
</div>
</div>
}
</fieldset>
)
render() {
const { inputField, props } = this
const { handleSubmit, submitting } = props
return (
<div className="habbo-login-form">
<form className="login-form__form" onSubmit={handleSubmit}>
<Field name="username" type="text" component={inputField} label="Username" />
<Field name="password" type="password" component={inputField} label="Password" />
<button className="login-form__button" type="submit" disabled={submitting}>Let's go!</button>
</form>
<div className="login-form__social">
<div className="habbo-facebook-connect" type="large">
<button className="facebook-connect">Login with Facebook</button>
</div>
<div className="habbo-facebook-connect" type="small">
<button className="facebook-connect"></button>
</div>
</div>
</div>
)
}
}
And the HOC LoginHeader:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import classNames from 'classnames'
import LoginForm from './LoginForm'
import { authActions } from '../redux/modules/auth'
#connect(
state => ({
user: state.auth.user,
...state.form.loginForm
}),
{ ...authActions }
)
export default class LoginHeader extends Component {
static propTypes = {
user: PropTypes.object,
login: PropTypes.func.isRequired,
logout: PropTypes.func.isRequired
}
static contextTypes = {
router: PropTypes.object
}
onSubmit = (data) => this.props.login(data).then(console.log)
render() {
const { submitFailed } = this.props
const headerLoginForm = classNames(
'header__login-form',
submitFailed ? 'animated shake' : ''
)
return (
<div className="header__top sticky-header sticky-header--top">
<div className="wrapper">
<div className="header__top__content">
<div className={headerLoginForm}>
<LoginForm onSubmit={this.onSubmit} />
</div>
</div>
</div>
</div>
)
}
}
Even when I try to replace <form onSubmit={handleSubmit}> with <form onSubmit={(e) => e.preventDefault()}> my page still refreshes.
I'm unsure whether or not this is a problem with my coding, browser, version, or whatever else because practically yesterday it worked without any problem.

Resources