Error in App.js when trying to launch local React testing when switching to using hooks - node.js

I'm working on a project for my internet programming class and I'm not quite sure where I made my mistake here. I had this project at least running and able to test locally up until last night when I switched to using hooks (or trying to anyway). When I run npm start this is what logs into the console on Firefox.
Uncaught TypeError: this is undefined
App App.js:67
React 11
workLoop scheduler.development.js:266
flushWork scheduler.development.js:239
performWorkUntilDeadline scheduler.development.js:533
js scheduler.development.js:571
js scheduler.development.js:633
factory react refresh:6
Webpack 24
App.js:67
App App.js:67
React 11
performConcurrentWorkOnRoot self-hosted:1406
workLoop scheduler.development.js:266
flushWork scheduler.development.js:239
performWorkUntilDeadline scheduler.development.js:533
(Async: EventHandlerNonNull)
js scheduler.development.js:571
js scheduler.development.js:633
factory react refresh:6
Webpack 24
I had not changed any of my import statements, I had only added useState. VSCode shows me no errors in my code, so I believe something is out of place, but that's why I'm here to ask.
//import logo from './logo.svg';
import './App.css';
import './form.css';
import React, { useState } from 'react';
function App(){
const [showText, setShowText] = useState(0);
const radioHandler = (showText) => {
setShowText(showText);
};
// constructor = (props) => {
// super(props);
// this.state = {
// status: 0
// };
// handleInputChange = handleInputChange.bind(this);
// handleSubmit = handleSubmit.bind(this);
// }
const handleInputChange = (event, value) => {
console.log(value);
}
const handleSubmit = (event) => {
event.preventDefault();
}
return (
<div className="form_css">
<form onSubmit={handleSubmit}>
<div className="general_info_container">
<div className="name_container">
<label className="f_name">First Name:</label>
<input
name="f_name"
type="text"
value={this.state.f_name}
onChange={handleInputChange}
placeholder="Please enter your first name"
/>
<label className="m_name">Middle Initial:</label>
<input
name="m_name"
type="text"
value={this.state.m_name}
onChange={handleInputChange}
placeholder="Please enter your middle initial"
/>
<label className="l_name">Last Name:</label>
<input
name="l_name"
type="text"
value={this.state.l_name}
onChange={handleInputChange}
placeholder="Please enter your last name"
/>
</div>
<div className="address_container">
<label>Street:</label>
<input
className="street"
type="text"
value={this.state.street}
onChange={handleInputChange}
placeholder="123 Main Street"
/>
<label>City:</label>
<input
className="city"
type="text"
value={this.state.city}
onChange={handleInputChange}
placeholder="City Name"
/>
<label>State:</label>
<input
className="state"
type="text"
value={this.state.state}
onChange={handleInputChange}
placeholder="New York"
/>
<label>Zip Code:</label>
<input
className="zip_code"
type="number"
value={this.state.zip_code}
onChange={handleInputChange}
placeholder="12345"
/>
</div>
<div>
<label>
Have you exercised regularly within the past six (6) months?
</label>
<input
className="exr_yes"
type="radio"
value="true"
onChange={handleInputChange}
/>
<input
className="exr_no"
type="radio"
value="false"
onChange={handleInputChange}
/>
<br></br>
{/* Testing radio button hide/show */}
<label>Do you have any chonic medical conditions? TEST TEST TEST TEST TEST TEST</label>
<input
className="chronic_yes"
type="radio"
value="true"
checked={showText === 1}
onClick={(e) => radioHandler(1)}
/>
<input
className="chronic_no"
type="radio"
value="false"
checked={showText === 2}
onClick={(e) => radioHandler(2)}
/>
{showText === 1 &&
<div>
<p>Test showing</p>
</div>}
{showText === 2 & <p></p>}
<div>
<label>Please enter any chronic conditions you have below:</label>
<input
className="chronic_medical"
type="text"
value={this.state.chronic_show}
onChange={handleInputChange}
/>
</div>
{/* Testing radio button hide/show
{/* Testing radio button hide/show */}
<label>Are you currently taking any medication?</label>
<input
className="meds_yes"
type="radio"
value="chronic"
onClick={(e) => radioHandler(1)}
/>
<input
className="meds_no"
type="radio"
value="chronic"
onClick={(e) => radioHandler(2)}
/>
<div id="meds_show">
<label>Please list any medications you take below:</label>
<input
className="meds_show"
type="text"
value={this.state.meds_show}
onChange={handleInputChange}
/>
</div>
{/* Testing radio button hide/show */}
{/* Testing radio button hide/show */}
<label>Do you, or have you had, any injuries?</label>
<input
className="injury_yes"
type="radio"
value="ture"
onChange={handleInputChange}
/>
<input
className="injnury_no"
type="radio"
value="false"
onChange={handleInputChange}
/>
<div id="injury_show">
<label>
Please enter any injuries you have had in the past below:
</label>
<input
className="injury_show"
type="text"
value={this.state.injury_show}
onChange={handleInputChange}
/>
</div>
{/* Testing radio button hide/show */}
<label>
Has a doctor ever suggested you only participate in medically
supervised exercise?
</label>
<input
className="supexr_yes"
type="radio"
value={this.state.supexr_yes}
onChange={handleInputChange}
/>
<input
className="supexr_no"
type="radio"
value={this.state.supexr_no}
onChange={handleInputChange}
/>
</div>
</div>
</form>
</div>
);
}
export default App;
And please, if you have any tips for a beginner they would be much appreciated!

The error is telling you exactly what is going wrong: this is being referenced and is undefined.
I can see you've commented out some lines, which looks as though you've moved away from using Class components to Functional components. Class components would understand this, but as you're now using a Functional component constructs like this.state.f_name are meaningless.
I don't want to re-write your code, but just want to point out that you probably want to do something like:
const [firstName, setFirstName] = useState("");
....
const handleInputChange = (event, value) => {
if(event.target.name == 'f_name'){
setFirstName(value);
}
console.log(value);
}
...
<input
name="f_name"
type="text"
value={firstName}
onChange={handleInputChange}
placeholder="Please enter your first name"
/>
You need to do something similar for all other input fields, and then tidy up the code.
I suggest you always start with something small (remove all other fields and just get one field working).
https://reactjs.org/docs/getting-started.html is an external starting place to get a better understanding of React. Happy coding.

You use this.state in your input field value but you are using hooks. You can create all your state variable using useState. Like the below:
const [inputValue, setInputValue] = useState({
f_name: '',
m_name: '',
...
})
return (
<div>
...
<input
name="f_name"
type="text"
value={inputValue.f_name}
onChange={handleInputChange}
placeholder="Please enter your first name"
/>
</div>
)

Related

Angular 13 - Data is accessible inside component, but does not show on the html page

So, I am learning Angular right now, and tried doing a CRUD Application. Almost everything works, except when trying to get data using ID, I can access all the data in the component.ts file, but the same is not rendered into html file. Here is what I have tried :-
edit-to.component.ts
export class EditTodoComponent implements OnInit {
private tid: number = 0;
public Todo:TodoModel= null ;
public desc:string='';
public title:string='';
public id:number;
constructor(private route: ActivatedRoute, private http:HttpClient) { }
ngOnInit(): void {
this.route.paramMap.subscribe(all_params =>{
this.tid = parseInt(all_params.get('id'))
//console.log( all_params.get('id'))
//console.log( this.tid );
});
this.getTodoFromId(this.tid)
}
getTodoFromId(id){
//console.log("id="+id)
this.http.get<{data: any}>('http://localhost:3000/api/todos/get_todo_from_id/'+id).subscribe((data) =>{
console.log("response in angular= \n");
this.Todo = data[0]
console.log(this.Todo.todo_title) //-> This one works
}
editOnSubmit(form:NgForm){
//something here
}
edit-todo.component.html
<div class="col-md-12">
<form (ngSubmit)="editOnSubmit(todoForm)" #todoForm="ngForm">
<input type="text" class="form-control" id="todo_id" [(ngModel)]="id" name="todo_id" value="1">
<div class="mb-3">
<label for="todo_title" class="form-label">Title</label>
<input type="text" class="form-control" id="todo_title" [(ngModel)]="title" name="title" value="{{ Todo.todo_title}}"> //-> This one does not work.
</div>
<div class="mb-3">
<label for="label" class="form-label">Description</label>
<textarea class="form-control" id="todo_description" [(ngModel)]="desc" name="desc" ></textarea>
</div>
<button type="submit" class="btn btn-success">Edit To Do</button>
</form>
</div>
</div>
Separating out,
from edit-to.component.ts :-
console.log(this.Todo.todo_title) works
but from edit-todo.component.html
<input type="text" class="form-control" id="todo_title" [(ngModel)]="title" name="title" value="{{ Todo.todo_title}}"> does not work
it's because you have a ngModel and a value configured on same input field
in this situation the ngModel have priority on value attribute
to fix it you can initialize title in ngOnInit
this.title = this.Todo.todo_title;
in your case you wait reply from http request so the initialization after hte http reply :
getTodoFromId(id){
this.http.get<{data: any}>('http://localhost:3000/api/todos/get_todo_from_id/'+id).subscribe((data) =>{
console.log("response in angular= \n");
this.Todo = data[0]
this.title = this.Todo.todo_title;
console.log(this.Todo.todo_title);
}
Define a property of type BehaviorSubject.
isAvailableData = new BehaviorSubject<boolean>(true);
Then where you subscribe the data set it to true.
getTodoFromId(id){
//console.log("id="+id)
this.http.get<{data: any}>('http://localhost:3000/api/todos/get_todo_from_id/'+id).subscribe((data) =>{
console.log("response in angular= \n");
this.Todo = data[0];
this.isAvailableData.next(true);
console.log(this.Todo.todo_title) //-> This one works
}
after that in your HTML add ngIf to col-md-12 div:
<div class="col-md-12" *ngIf="(isAvailableData | async)">
<form (ngSubmit)="editOnSubmit(todoForm)" #todoForm="ngForm">
<input type="text" class="form-control" id="todo_id" [(ngModel)]="id" name="todo_id" value="1">
<div class="mb-3">
<label for="todo_title" class="form-label">Title</label>
<input type="text" class="form-control" id="todo_title" [(ngModel)]="title" name="title" value="{{ Todo.todo_title}}"> //-> This one does not work.
</div>
<div class="mb-3">
<label for="label" class="form-label">Description</label>
<textarea class="form-control" id="todo_description" [(ngModel)]="desc" name="desc" ></textarea>
</div>
<button type="submit" class="btn btn-success">Edit To Do</button>
</form>
Also you made a mistake in your form the input should be like below:
And there is no need to define a property for id, title, ...
These are the properties of todo object
<label for="todo_title" class="form-label">Title</label>
<input type="text" class="form-control" id="todo_title" [(ngModel)]="Todo.todo_title" name="todo_title" #todo_title="ngModel">

Disabling Font Awesome Icon

I am building a search bar which I want to be disabled unless the user enters something. Appreciate any help to make this work.
This is my handlebars code:
<div class="searchWrapper">
<form action="/founduser" method="POST" class="searchBar">
<input type="hidden" id="groupid" name="groupid" value={{this.groupid}}>
<input type="text" name="searchBar" id="searchBar" placeholder="Enter the user's email ID"
value="{{this.term}}" />
{{!-- <i class="fas fa-search"></i>
<input type="submit" value="" id="submit"> --}}
<button type="submit" class="btn-search" id="user-search-btn"><span class="icon search"
disabled></span></button>
</form>
</div>
and I am running a JS check to alternate
const searchButton = document.getElementById('user-search-btn');
const check = () => {
if (searchButton !== "") {
searchButton.disabled = false
} else {
searchButton.disabled = true
}
}
searchButton.onkeyup = check
Where am I going wrong?
Sorry, I figured where I was going wrong. In my code I was checking if searchButton was empty, however what I should have done was to check the value inside the <input type="text" name="searchBar" id="searchBar" placeholder="Enter the user's email ID" value="{{this.term}}" />.

How to integrate 2checkout with reactjs and nodejs?

I am trying to integrate 2checkout API in my reactjs &nodejs project.I reffered the documents which 2co provided.I created an account and in that webhooks&API i have "Merchant Code" and "Secret Key" but there is no "Publishable key" and "Private Key" Why?
what i have is:
render = () => {
return(
<form id="myCCForm" onSubmit={this.Submit}>
<input
id="token"
name="token"
type="hidden"
value=""
></input>
<div>
<label>
<span>Card Number</span>
</label>
<input
id="ccNo"
type="text"
size="20"
value=""
autocomplete="off"
required
/>
</div>
<div>
<label>
<span>Expiration Date (MM/YYYY)</span>
</label>
<input
type="text"
size="2"
id="expMonth"
required
></input>
<span> / </span>
<input
type="text"
size="2"
id="expYear"
required
></input>
</div>
<div>
<label>
<span>CVC</span>
</label>
<input
id="cvv"
size="4"
type="text"
value=""
autocomplete="off"
required
></input>
</div>
<input type="submit" value="Submit Payment"></input>
</form>
)}
submit=()=>{
let args = {
sellerId: "",//gave merchant code here
publishableKey: "",//as there is no publishable key what will give here?
ccNo: "",
cvv: "",
expMonth: "",
expYear: ""
};
window.TCO.loadPubKey("sandbox", () => {
window.TCO.requestToken(args).then(data => {
console.log("data");
});
});
How can i resolve this problem?

netlify form submission not showing file on the back end, all other fields are showing up but not the file upload

Even though it is mostly from the netlify site, I can't seem to figure out why the file upload doesn't work. What I get on the other end is all the fields, but the file upload comes back blank with no error in the console. Looked at videos and online instructions and don't see what the difference is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Contact</title>
<script src="https://unpkg.com/react#16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom#16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone#6.15.0/babel.min.js"></script>
</head>
<body>
<!-- A little help for the Netlify post-processing bots -->
<form name="contact" netlify hidden>
<input type="text" name="name" />
<input type="text" name="CompanyName" />
<input type="text" name="Address" />
<input type="text" name="PrimaryContact" />
<input type="text" name="SecondaryContact" />
<input type="email" name="email" />
<textarea name="message"></textarea>
<input type="file" name="myFile"/>
</form>
<div id="root"></div>
<script type="text/babel">
const encode = (data) => {
return Object.keys(data)
.map(key => encodeURIComponent(key) + "=" + encodeURIComponent(data[key]))
.join("&");
}
class ContactForm extends React.Component {
constructor(props) {
super(props);
this.state = { name: "",CompanyName:"",Address:"",PrimaryContact:"", SecondaryContact:"", email: "", message: "" , myFile:""};
}
/* Here’s the juicy bit for posting the form submission */
handleSubmit = e => {
fetch("/", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({ "form-name": "contact", ...this.state })
})
.then(() => alert("Success!"))
.catch(error => alert(error));
e.preventDefault();
};
handleChange = e => this.setState({ [e.target.name]: e.target.value });
render() {
const { name,CompanyName, Address, PrimaryContact,SecondaryContact,email, message,myFile } = this.state;
return (
<form onSubmit={this.handleSubmit} data-netlify-recaptcha="true" data-netlify="true">
<p>
<label>
Your Name: <input type="text" name="name" value={name} onChange={this.handleChange} required/>
</label>
</p>
<p>
<label>
Company Name: <input type="text" name="CompanyName" value={CompanyName} onChange={this.handleChange} />
</label>
</p>
<p>
<label>
Address: <input type="text" name="Address" value={Address} onChange={this.handleChange} />
</label>
</p>
<p>
<label>
Primary Contact: <input type="text" name="PrimaryContact" value={PrimaryContact} onChange={this.handleChange} />
</label>
</p>
<p>
<label>
Secondary Contact: <input type="text" name="SecondaryContact" value={SecondaryContact} onChange={this.handleChange} />
</label>
</p>
<p>
<label>
Your Email: <input type="email" name="email" value={email} onChange={this.handleChange} />
</label>
</p>
<p>
<label>
Ticket Discription: <textarea name="message" value={message} onChange={this.handleChange} />
</label>
</p>
<p>
<input type="file" name="myFile" placeholder="Upload File" />
</p>
<p>
<button type="submit">Send</button>
</p>
</form>
);
}
}
ReactDOM.render(<ContactForm />, document.getElementById("root"));
</script>
</body>
</html>
I had a similar issue and was able to solve it using this checklist from the Netlify community:
6. Make sure that you POST your form request (not GET) with a Content-Type of application/x-www-form-urlencoded in most cases. However, if and only if you are submitting the form with a file upload then the Content-Type needs to be multipart/form-data instead.
from: [Common Issue] Form problems, form debugging, 404 when submitting
Moving to a different Content-Type solved a similar issue for me. Then again I'm not using fancy Javascript/Ajax form submission so all it took was to add an enctype="multipart/form-data" attribute to my form tag. In your case it will require reworking your encode function.
I also had a similar issue.
Removing the headers option from the fetch() function did it for me.
Ex:
fetch("/", {
method: "POST",
// headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: encode({ "form-name": "contact", ...this.state })
})

How to fix you need to enable javascript to run this app in react app?

I am getting error you need to enable javascript to run this app. when I run using nom start.
I have tried to change browser settings. but didn't work please see screenshots that I have attached.
class AuthPage extends Component {
render() {
return (
<form className="auth-form">
<div className="form-control">
<label htmlFor="email">E-Main</label>
<input type="email" id="email" />
</div>
<div className="form-control">
<label htmlFor="password">Password</label>
<input type="password" id="password" />
</div>
<div className="form-actions">
<button type="button">Switch To SIGN UP</button>
<button type="submit">Submit</button>
</div>
</form>
);
}
}

Resources