preventDefault() not working on submit in React - reactjs

I'm currently working in react and have a couple of forms where the onSubmit functions automatically refresh the page even if I use preventDefault(). Im passing the event into the functions as well. Could really use some guidance on why these two forms are having this issue. It hasn't been a problem elsewhere.
Here's the form. Verify is automatically passing e.
<form onSubmit={verify} className='username-password-form'>
<div className='old-password-container'>
<label className='old-password-label'>Current Password:</label>
<input
className='old-password-input'
type='password'
id={`${id}-old-password`}
value={currentPassword}
name='currentPassword'
disabled={disabled}
onChange={(e) => setCurrentPassword(e.target.value)}
/>
<Button className='submit-old' type='submit'>
Submit
</Button>
</div>
</form>
Here's the verify function called onSubmit
const verify = async (e) => {
e.preventDefault();
const user = {
username: user_name,
password: currentPassword,
};
await fetch('http://localhost:3000/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(user),
});
setDisabled(true);
};

Related

Trouble with React Form POST request

I am having difficulty understanding what I'm doing wrong on this POST request. The POST request itself is working which I confirmed in the network tab.
However, I am only able to post static values that I define, rather than the values from the form fields. Please have a look. This is driving me up the wall. Thank you!
Notes:
In TestForm.js it doesn't actually seem to console.log the response as I'm asking it to.
I receive no errors.
This does POST to my server, and into Postgres, and I will show below what that looks like when I console.log.
console.log(sauces) at the start of HandleSubmit does in fact show "sauces" currectly, which is whatever is input into the first form field.
GitHub Repository
The React Form Component (TestForm.js):
function TestForm() {
const [sauce, setSauce] = useState('');
const [presentation, setPresentation] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
fetch('http://jyh:3000', {
method: 'POST',
headers: {'Content-Type':'application/json'},
body: JSON.stringify({
"test_name": sauce,
"test_sauce": presentation,
}),
}).then((res) => {
console.log(res.json());
return res.json();
}).catch((err) => {
console.log(err.message);
});
};
return (
<form onSubmit={handleSubmit}>
<div className="color-section" id="reviewASauce">
<div className="container-fluid">
<h2>Review a Sauce</h2><br />
Trying a sauce that is already in our database? Review it!
<br />
<br />
<br />
<h2>Sauce Name</h2>
<Form.Label htmlFor="test_name">
</Form.Label>
<Form.Control
type="text"
id="test_name"
aria-describedby="test_name"
placeholder="Input the name of the sauce here."
value={sauce}
onChange={(e) => setSauce(e.target.value)}
/>
<Form.Text id="test_name" muted>
</Form.Text>
<br />
<br />
<Form.Label htmlFor="test_sauce">
</Form.Label>
<Form.Control
type="text"
id="test_sauce"
aria-describedby="test_sauce"
placeholder="Input the name of the sauce here."
value={presentation}
onChange={(e) => setPresentation(e.target.value)}
/>
<Form.Text id="test_sauce" muted>
</Form.Text>
<br />
<br />
<Button variant="dark" type="submit">
Submit
</Button>
</div>
</div>
</form>
);
}
export default TestForm;
Server index.js:
app.post('/', async (req, res) => {
await TestTable.create({
test_name: "test_name",
test_sauce: "test_sauce",
}).then((data) => {
console.log(data.toJSON());
}).catch((err) => {
console.log(err);
});
});
What the terminal displays when clicking submit:
{
id: 100,
test_name: 'test_name',
test_sauce: 'test_sauce',
updatedAt: 2022-12-21T02:54:42.447Z,
createdAt: 2022-12-21T02:54:42.447Z
}
I have tried to change and arrange both the HandleSubmit function as well as my app.post, but no matter what I do I cannot seem to get the form data from TestForm.js to index.js.
In your Server index.js you are not using the params you sent from the frontend.
It looks you are using express for you server.
Try doing something like
await TestTable.create({
test_name: req.body.test_name,
test_sauce: req.body.test_sauce
})
Check this: How to access the request body when POSTing using Node.js and Express?

image file isnt being read by react

I am using formData to send details to my backend but somehow my image path isn't being sent.
Post photo
<div className="form-group">
<label className="btn btn-block btn-success">
<input
onChange={handleChange("photo")}
ref={inputRef}
type="file"
name="photo"
accept="image"
placeholder="choose a file"
/>
</label>
</div>
this is the form i am using
Handle change and submit button
const onSubmit = (event) => {
event.preventDefault();
setValues({...values,error:"",loading:true});
createProduct(user._id,token,JSON.stringify(values))
.then(data=>{
if(data.error){
setValues({...values,error:data.error});
}else{
setValues({...values,
name:"",
description:"",
price:"",
photo:"",
stock:"",
createdProduct:data.name,
loading:false});
}
}).then(response=>{
})
.catch(err=>console.log(err));
//
};
const handleChange = name => event => {
const value=name==="photo"?event.target.files[0]:event.target.value;
formData.append(name,value)
setValues({...values,[name]:value});
//
};
And this is the api call to backend
export const createProduct=(userId,token,product)=>{
console.log(product)
return fetch(`${API}/product/create/${userId}`,{
method: "POST",
headers:{
Accept: "application/json",
Authorization: `Bearer ${token}`
},body:product
})
.then(response=>{
return response.json();
})
.catch(err=>console.log(err));
}
The api is working fine with postman , I am using formidable in backend. Some answers from stack made the path of the file have c:\fakepath and so m too confused what to do .
Thanks for help.

Make a POST form-data with React to upload an image

I am trying to upload an image within my ReactJS service to my NestJS API service, through my API, but it's not working yet. This is the React code:
First the form:
<div>
<input type="file" name="urlpromo" value={urlpromo} onChange={this.changeHandler} />
</div>
<button type="submit">Submit</button>
and the functions:
changeHandler = (e) => {
this.setState({[e.target.name]: e.target.value})
}
submitBaner = (e) => {
var bodyFormData = new FormData();
bodyFormData.append('file', this.state.urlpromo);
let config = {
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
}
}
e.preventDefault()
console.log(bodyFormData)
axios.post('http://localhost:3000/images/upload', bodyFormData,config)
}
The thing is that before I was sending images, only with JSON body, it was working fine, but now with form-data, I cant make it work. This is how I can upload an image with Postman:
When I try to make it work, the function console log prints this:
FormData {}__proto__: FormData
What I am doing wrong, how should I work with this form-data?
As per the docs, <input type="file"> is uncontrolled due to its read-only value.
One option is to use a ref to track the <input> element and the files property to access the File
// in your constructor
this.urlPromoRef = React.createRef()
<div>
<input type="file" ref={this.urlPromoRef} />
</div>
<button type="submit">Submit</button>
and in your submit handler
e.preventDefault()
const bodyFormData = new FormData();
bodyFormData.append('file', this.urlPromoRef.files[0]);
// no need for extra headers
axios.post('http://localhost:3000/images/upload', bodyFormData)
Another option is to simply pass the <form> itself into the FormData constructor.
<form onSubmit={this.submitBaner}>
<div>
<input type="file" name="urlpromo" /> <!-- must have a name -->
</div>
<button type="submit">Submit</button>
</form>
submitBaner = (e) => {
e.preventDefault()
const bodyFormData = new FormData(e.target); // pass in the form
axios.post('http://localhost:3000/images/upload', bodyFormData)
}
Finally, you may be able to use something like your original code but with a special check for <input type="file">. Eg
changeHandler = (e) => {
const el = e.target
this.setState({
[el.name]: el.type === "file" ? el.files[0] : el.value
})
}

How to make post request with form in React

After i filled the inputs and submitted the form, I want to make a POST request with React. When i use fetch outside the handleSubmit function with a static name and job value, it works. But if i use inside the handleSubmit function, it doesn't work. Why? and how can i solve this?
import React from "react";
function CreateUser() {
const handleSubmit = (e) => {
e.preventDefault();
fetch("https://reqres.in/api/users", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
name: `${e.target.name.value}`,
job: `${e.target.job.value}`,
}),
})
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
};
return (
<form onSubmit={handleSubmit}>
<label htmlFor="name">Name</label>
<input id="name" name="name" type="text" />
<label htmlFor="job">job</label>
<input id="job" name="job" type="text" />
<input type="submit" value="submit" />
</form>
);
}
export default CreateUser;
Can you check how to use fetch correctly. https://developers.google.com/web/ilt/pwa/working-with-the-fetch-api you need to return response.
Your react code seems fine, not sure how are you trying to handle success and error.
Check following Sandbox which I created using your code.
https://codesandbox.io/s/adoring-breeze-7fx2g?file=/src/App.js

Handling PUT request in React?

I am a beginner in both React and Spring Boot and I realized how this might be a really easy question, but I had a problem in understanding how to handle PUT requests in React. I have a form as the following:
<Form onSubmit={this.handleSubmit}>
<FormGroup>
<Label>Description</Label>
<Input type="text" name="description" onChange={this.handleChange}/>
</FormGroup>
<FormGroup>
<Label>Category</Label>
<select onChange={this.handleChangeCategory}>{optionList}</select>
</FormGroup>
<FormGroup>
<Label>Date</Label>
<DatePicker selected={this.state.item.timeStamp} onChange={this.handleChangeDate}/>
</FormGroup>
</Form>
This is the item object in the state:
item: {
timeStamp: new Date(),
description: ''
category: {id: '', categoryName: ''}
}
And I have an "update" button as the following:
expenses.map (expense =>
<Button size="sm" color="secondary" onClick={ () => this.update(expense.id)}>Update</Button>
The update() is as following:
async update(id) {
// I want to populate the form with the data from expense.id the user clicked on
const response = await fetch(`/api/expenses/${id}`); // GET endpoint from Spring Boot
const body = await response.json();
this.setState( {item: body});
// Handling PUT request
await fetch(`api/expenses/${id}`, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
});
updatedItem = {...this.state.item}; // Getting the updated item
this.setState({item: updatedItem}); // I want to be able to update the state like this
this.props.history.push('/expense');
}
I want to be able to populate the form with the data from the expense.id the user clicked on and I had the logic of getting the GET method from the endpoint in Spring Boot but it did not work. I am also confused on how handle the PUT request after the user updated the form. Sorry if it is a stupid question. Any help would be appreciated, thanks alot!

Resources