unable to display response from post request in react - reactjs

i am new to react development.
I am able to get response from post request and print in console but nt sure how to display it on main page.
code from app.js for my ui
render() {
return (
<div className="App">
<h1>Enter Email Address to Verify</h1>
<h1>{this.state.response.body}</h1>
<form onSubmit={this.handleSubmit}>
<p>
<strong>Address:</strong>
</p>
<input
type="text"
value={this.state.post}
onChange={e => this.setState({ post: e.target.value })}
/>
<button type="submit">check</button>
</form>
</div>
);
}
this is the way i get it print on console
console.log(wellFormed, validDomain, validMailbox);
handleSubmit = async e => {
e.preventDefault();
const response = await fetch('/api/v1/verifier', {
method: 'POST',
// body: this.state,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ post: this.state.post }),
});
const body = await response.text();
this.setState({ responseToPost: body });
};
From verifier method
res.send(
`response received , welllformed = ${wellFormed}, validDomain = ${validDomain}, validMailbox = ${validMailbox}`,
)

Most of the time you will get a JSON response which is nothing but an Array of objects. So you can put that to a state then use higher order function map to render each element to the Dom.
let's assume that your response is like this.
[{"activeCases":"5132472","country":"USA"} ,"activeCases":"455602","country":"India"}]
you can refer each object as course(it can be any name) inside the map method.
{this.state.response.map((course) => (
<div>
<h3>Active cases :{course.activeCases}</h3>
<h5>country :{course.country}</h6>
</div>
))}
This will render each data in your repose to the Dom like thise.
Active cases :5132472
country :USA
Active cases :455602
country :India

render() {
return (
<div className="App">
<h1>Enter Email Address to Verify</h1>
<h2>{this.state.response.body}</h2>
<form onSubmit={this.handleSubmit}>
<p>
<strong>Email Address:</strong>
</p>
<input
type="text"
value={this.state.post}
onChange={e => this.setState({ post: e.target.value })}
/>
<button type="submit">Verify</button>
</form>
<p>{this.state.responseToPost}</p>
</div>
);
}
This worked for me

Related

Leadspedia Form Submission does not work with onSubmit

I have a form in React that I'm trying to submit to Leadspedia, but I'm seeing strange behavior. The instructions from Leadspedia API shows an example of using the method and action options to send the form. I'd like to use the onSubmit event handler to have more control of the form, but for some reason that returns with an error. Using their example submits correctly. Here is my code:
const postData = async (url = '', data = {}) => {
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
});
return response.json();
}
const handleSubmit = async (e) => {
e.preventDefault();
const url = "*leadspedia end point*";
const data = formValues;
postData(url, data)
.then((data) => {
console.log(data)
})
.catch(error => {
console.log(error)
})
resetForm(
Here is my form:
<form
style={{ width: '100%'}}
onSubmit={handleSubmit}
id="lp_form"
action="*leadspedia endpoint*"
method="post"
>
<div>
{formSections?.[formStep]?.fields?.map((field, index) => (
renderInput(field, index)
))}
{Object.keys(formValues).map((key, index) => (
<input key={index} type="hidden" name={key} value={formValues[key]} />
))}
<input type="hidden" id="lp_offer_id" name="lp_offer_id" value={offerId} />
<input type="hidden" id="lp_campaign_id" name="lp_campaign_id" value={campaignId} />
<input type="hidden" id="lp_campaign_key" name="lp_campaign_key" value={campaignKey} />
</div>
<div>
{formStep === 9 && (
<Button type="submit" variant="primary">
Submit
</Button>
)}
</div>
</form>
Submitting without the handleSubmit function works perfectly fine. However, submitting the form with the handleSubmit function returns a response that says Invalid campaign key or id. I've checked the values multiple times and it's the correct key and id. Am I missing something the handleSubmit function that would cause this error?

Unable to make a PATCH request using radio buttons in ReactJS

I am trying to add in a list of tasks and want to change them to either "Complete" or "Not Complete" using radio buttons and then updating it to send a PATCH request to the data to update. When I press update nothing changes on the data.
This is the code I have for this page:
`
function ProjectDetails() {
const [WaxProcedure, setWaxProcedure] = useState("");
const { id } = useParams();
const {
data: project,
error,
isPending,
} = useFetch(`http://localhost:8000/ProjectsData/${id}`);
const history = useNavigate();
const handleClickDelete = () => {
fetch(`http://localhost:8000/ProjectsData/${id}`, {
method: "DELETE",
}).then(() => {
history("/");
});
};
const handleUpdate = () => {
fetch(`http://localhost:8000/ProjectsData/${id}`, {
method: "PATCH",
headers: {
"Content-type": "application/json",
body: JSON.stringify(project),
},
}).then((response) => {
response.json();
});
};
return (
<div className="project-details">
{isPending && <div>Loading...</div>}
{error && <div>{error}</div>}
{project && (
<article>
<h1>{project.Customer}</h1>
<h2>
{project.Part} {project.Description}
</h2>
<h2>{project.Tool}</h2>
<div>Project Status: {project.Stage}</div>
<p>Lead engineer: {project.Engineer}</p>
<div className="procedure-list">
<form onSubmit={handleUpdate}>
Wax: <p>{WaxProcedure}</p>
<input
type="radio"
name="waxprocedure"
value="Not Complete"
required
onChange={(e) => setWaxProcedure(e.target.value)}
/>
Not Complete
<input
type="radio"
name="waxprocedure"
value="Complete"
required
onChange={(e) => setWaxProcedure(e.target.value)}
/>
Complete
<button type="submit" onClick={handleUpdate}>
Update
</button>
</form>
</div>
<button type="submit" onClick={handleClickDelete}>
Delete
</button>
</article>
)}
</div>
);
}
`
Any ideas why the data won't update? I am new to this and spent a long time trying to find an answer.
I have tried the patch request on Postman and this worked too, so nothing wrong with the request.
remove "onsubmit" from form tag and remove type="submit" from both buttons and pass "project" parameter to handleupdate method

Why isnt my pic getting displayed after using Active Storage?

I am trying to implement active storage .And have been following along with this article .Its a very very short article https://dev.to/jblengino510/uploading-files-in-a-react-rails-app-using-active-storage-201c.The backend has been set correctly as instructed...The only problem is in the front end..I am not able to write my React project code in a way thats similar to this project and hence im lacking a correct code.
Here is my Project code
The add review form card
function AddReviewForm({user,handleAddReviews}){
const params = useParams();
const[img,setImg]=useState("");
const[r,setR]=useState("");
const[imgData,setimgData]=useState("");
const newReview = {
img,
r,
imgData,
restaurant_id: params.id,
user_id: user.id,
};
const configObj = {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(newReview),
};
function handleReviewSubmit(event) {
event.preventDefault();
fetch(`/reviews`, configObj)
.then((r) => r.json())
.then((review)=>{
handleAddReviews(review);
setR('')
setImg('')
setimgData('')
}
);
}
return (
<>
<h1>Add review form</h1>
<form onSubmit={handleReviewSubmit}>
<div>
<input type="file"
name="picture"
accept="image/png, image/gif, image/jpeg"
id="picture"
onChange={(e)=>setimgData(e.target.files[0])} />
</div>
<div>
<label htmlFor="r" >Review</label>
<input type="text" name="r" value={r} onChange={(e) => setR(e.target.value)} placeholder="review" />
</div>
<input type="submit" />
</form>
</>
)
}
export default AddReviewForm;
And the displayed ReviewCard.js
import { useParams } from "react-router-dom";
function ReviewCard({review,user,handleDelete}){
const{id,img,r,picture,user:reviewuser}=review
function handleDeleteClick() {
fetch(`/reviews/${review.id}`, {
method: "DELETE",
})
handleDelete(review.id)
}
return(
<>
<img src={img}/>
<img src={picture} />
<p></p>
<p>{r}</p>
<h6>By {review.user.name}</h6>
{user.id===reviewuser.id&&<button onClick={handleDeleteClick} >Delete</button>}
</>
)
}
export default ReviewCard;
Pls help me out and lemme know what changed I can do so that my picture gets displayeddd

Passing data from front end to route in backend React

I am currently new to using React and express, I wish to send data which i have received from a form. The data i would like to send back is the UserInfo or email which is in the state. However I am extremely unsure how I am supposed to go about this request.
class ForgotPassword extends Component {
constructor() {
super()
this.state = {
email:'',
}
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
}
componentDidMount = () =>{
// this.fetchUserInfo();
}
handleChange = (e) => {
this.setState ({
[e.target.id]: e.target.value
})
console.log(this.state);
}
handleSubmit = async (e) => {
e.preventDefault();
const userInfo = {
email : this.state.email
};
fetch("/forgotpassword", {
method: "POST",
body: JSON.stringify(userInfo),
headers: { "Content-Type": "application/json" }
})
.then(response => {
return response.json();
})
.then(jsonData => {
console.log(jsonData);
})
.catch(err => {
console.log("Error with data fetch " + err);
});
};
This is my form...
<div className='row'>
<div className='col'></div>
<div className='col card form'>
<h1 id="title">Reset Password</h1>
<h5 id="passinstruc">Please enter your email to reset your password</h5>
<form id="forgotpass" onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="exampleInputEmail1">Email </label>
<input onChange={this.handleChange} type="email" className="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" value={this.state.email} />
<small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<button id="loginbtn" type="submit" className="btn btn-primary btn-lg btn-block" >Submit</button>
<br/>
<div className='division'>
<Link to="/register" className='btn btn-primary btn-lg btn-block' id="registerbtn" > Create your account here</Link>
</div>
</form>
</div>
In my backend I am getting a POST /forgotpassword 404 message but I dont know why. Help would be much appreciated.
This is my backend route where I will be sending the information
var express = require('express');
var router = express.Router();
var connection = require ('../connection');
var email = require ('./sendEmail');
router.post('/forgotpassword', function(req, res, next) {
console.log(req.email);
var userEmail = req.email;
var text = "Follow the instructions below to reset your password"
email.sendEmailWithTemplate(userEmail,'PetS.o.S Password Reset', text);
});
For sending data you will need the domain name or ip address of your server.
Once you obtained that, you can use jQuery.get - https://api.jquery.com/jQuery.get/
or jQuery.post -
https://api.jquery.com/jQuery.post/
Or if you are not using jQuery, use XMLHttpRequest -
https://www.w3schools.com/xml/xml_http.asp
Instead of sending data in body send it in response.
https://www.freecodecamp.org/news/create-a-react-frontend-a-node-express-backend-and-connect-them-together-c5798926047c/
fetch('/api/getList')
.then(res => res.json())
.then(list => this.setState({ list }))
https://dev.to/nburgess/creating-a-react-app-with-react-router-and-an-express-backend-33l3

'Uncaught SyntaxError: Unexpected token <' on Login Form

In my NextJS app.I'm developing a login page and now I'm getting the following error.
Uncaught SyntaxError: Unexpected token <
This was not appearing before and it started appearing yesterday.I googled the error message and browsed through many SO answers but none of them were helpful.I removed all form related onSubmit and onChange code but the error is still there.Since which code causes this error,I will post entire Login component here.
import React, { Component } from 'react';
import Heading from '../components/Heading';
class Login extends Component{
constructor(props) {
super(props);
this.onChangeInput = this.onChangeInput.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
date: new Date().toJSON().slice(0,10),
username: '',
password: ''
}
}
onChangeInput(e) {
this.setState({
[e.target.name]: e.target.value
});
}
onSubmit(e) {
e.preventDefault();
const t = {
date: new Date().toJSON().slice(0,10),
username: this.state.username,
password: this.state.password
}
fetch('/server', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify(this.state)
})
this.setState({
username: '',
password: ''
});
}
render(){
return(
<div>
<div style={{textAlign: "center"}}>
<h1>PackMasters Ceylon (Pvt) Ltd</h1>
<h2>Inventory Management System</h2>
<h3>Login</h3>
</div>
<form onSubmit={this.onSubmit} onChange={this.onChangeInput} className={"col-md-4 col-md-offset-4"}>
<Heading title="Login | PackMasters Ceylon (Pvt) Ltd" />
<div className={"form-group"}>
<label htmlFor="username">Username</label>
<input type="text" name="username" value={this.state.username} className={"form-control"} id="username"/>
</div>
<div className={"form-group"}>
<label htmlFor="passsword">Password</label>
<input type="password" name="password" value={this.state.password} className={"form-control"} id="password" />
</div>
<div className={"form-group"}>
<input type="submit" className={"form-control"} value="Log In"/>
</div>
</form>
</div>
);
}
}
export default Login;
After struggling a lot, I found out that it is caused by the browser cache.The problem was solved after clearing browser cache on Chrome.Still I'm not able to explain the exact reason for that.However I will mention here how to clear cache on Google Chrome.
On your computer, open Chrome.
At the top right, click More.
Click More tools > Clear browsing data.
At the top, choose a time range. To delete everything, select All time.
Next to "Cookies and other site data" and "Cached images and files," check the boxes.
Click Clear data
A few issues:
The change handler should go on each input, not on the form
A bad idea to set the timestamp in the constructor... Seems you were already going in the right direction...
If you convert the handlers into arrow functions (no this context) no need to bind in the constructor (that's just a side note...)
Try this:
import React, { Component } from 'react';
import Heading from '../components/Heading';
class Login extends Component {
state = { username: '', password: '' };
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = e => {
e.preventDefault();
const user = {
date: new Date().toJSON().slice(0, 10),
username: this.state.username,
password: this.state.password,
};
fetch('/server', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user),
});
this.setState({ username: '', password: '' });
};
render() {
return (
<div>
<div style={{ textAlign: 'center' }}>
<h1>PackMasters Ceylon (Pvt) Ltd</h1>
<h2>Inventory Management System</h2>
<h3>Login</h3>
</div>
<form
onSubmit={this.handleSubmit}
className={'col-md-4 col-md-offset-4'}
>
<Heading title="Login | PackMasters Ceylon (Pvt) Ltd" />
<div className={'form-group'}>
<label htmlFor="username">Username</label>
<input
type="text"
name="username"
value={this.state.username}
className={'form-control'}
id="username"
onChange={this.handleChange}
/>
</div>
<div className={'form-group'}>
<label htmlFor="passsword">Password</label>
<input
type="password"
name="password"
value={this.state.password}
className={'form-control'}
id="password"
onChange={this.handleChange}
/>
</div>
<div className={'form-group'}>
<input type="submit" className={'form-control'} value="Log In" />
</div>
</form>
</div>
);
}
}
export default Login;
Edit: Add a then and a catch block to fetch:
fetch('/server', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(user),
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
Also, I noticed you are using Next.js... You need to install Isomorphic Unfetch https://github.com/developit/unfetch/tree/master/packages/isomorphic-unfetch
In my case, static files were not being served due to global authentication enabled. which was also authenticating static files. So I had to apply #Public() metadata to that route to allow into JwtAuthGuard.
#Public()
#Get('/_next/static/*')
async getStaticContent(
#Req() req: IncomingMessage,
#Res() res: ServerResponse,
) {
await this.appService.handler(req, res);
}
More details on public metadata below.
https://docs.nestjs.com/security/authentication#enable-authentication-globally
And make sure your "esversion":6 is 6 for that follow below flow
For Mac VSCode : Code(Left top corner) => Prefrences => Settings => USER SETTINGS. and check at right side and write below Code
{
"workbench.colorTheme": "Visual Studio Dark",
"git.ignoreMissingGitWarning": true,
"window.zoomLevel": 0,
// you want to write below code for that
"jshint.options": {
"esversion":6
},
}

Resources