Submit formData with Reactjs doesn't work - reactjs

I'm trying to use formData() to submit a login form using Reactjs and Hooks, but it doesn't work.
Values returned from the formData components seem to be correct. I have try it both with Axios and Fetch and none of them work.
I have also tried different ways of populating the formData element, even with fixed strings, but none of them work.
I'm sure I'm making some naive mistake but, I can't find it.
Could some of you help me please?
Thank you
import React, {useState} from 'react'
import axios from 'axios'
function useLoginForm() {
const [field, setField] = useState({email: '', password: ''})
const changeHandler = (event) => {
setField({...field, [event.target.name]: event.target.value})
}
const onBlurHandler = (event) => {
setField({...field,[event.target.name]: event.target.value});
}
const fileHandler = (event) => {
console.log(event.target.files[0])
}
const submitHandler = async (event) => {
event.preventDefault();
for(let [name, value] of loginFormData) {
console.log(`KEY: ${name} VALUE = ${value}`);// Logging outcome details
}
const url = 'https://my_url/post'
}
console.log(`Submit --> ${field.email} - Password ${field.password}`);
try{
const response = await axios.post(url, loginFormData,{
headers: {
"Content-type": "multipart/form-data" /* ; boundary=${loginFormData._boundary}*/
},
}
)
console.log(response.data)
}catch(error){
console.log(error)
}
}
return (
<div>
<p>{field.email} - {field.password}</p>
<form id="loginForm" name="loginForm" onSubmit={submitHandler}>
<label htmlFor="email">email</label>
<input type="text" name="email" id="email" onChange={changeHandler} /* onBlur={onBlurHandler} */></input>
<label htmlFor="password">Password</label>
<input type="password" name="password" onChange={changeHandler} /* onBlur={onBlurHandler} */></input>
<input type="submit" value="Login" />
</form>
</div>
)
}
export default useLoginForm
Results:
KEY: email VALUE = xyz_xyz#VBM.com useLoginForm.js:47
KEY: password VALUE = Xxxxxx useLoginForm.js:47
Submit --> xyz_xyz#VBM.com - Password Xxxxxx useLoginForm.js:57
XHRPOSThttps://my_url/post
[HTTP/1.1 404 Not Found 6681ms]
1
-----------------------------345147470230284216993885766804
2
Content-Disposition: form-data; name="email"
3
4
xyz_xyz#VBM.com
5
-----------------------------345147470230284216993885766804
6
Content-Disposition: form-data; name="password"
7
8
Xxxxxx
9
-----------------------------345147470230284216993885766804--
10

Related

handleSubmit to call another function with event parameter

This is React JS.
I had a nice working sendData function that creates a new record on my json file.
It worked nice until I decided to add useForm to add some yup resolvers.
Now in the <form> tag here is onSubmit={}.
If I write here
<form onSubmit={handleSubmit(sendData(), onSubmit)}>, I get the error and nothing works as before.
enter image description here
I except to understand how handleSubmit works and how to resolve this problem.
Thanks in advance, guys!
my code:
import React, { useState } from 'react';
import { useForm } from 'react-hook-form';
import { Link, useNavigate } from 'react-router-dom';
import Confirmation from './Confirmation';
import * as yup from 'yup';
import { yupResolver } from '#hookform/resolvers/yup';
const schema = yup.object().shape({
name: yup.string().required(),
age: yup.number().positive().required(),
salary: yup.number().positive().required(),
email: yup.string().required(),
})
.required();
export default function LogIn() {
const { register, handleSubmit, formState: { errors }, } = useForm({
resolver: yupResolver(schema),
});
// for redirection
let navigate = useNavigate();
// modal for ghost mode
const [show, setShow] = useState(false);
const [details, setDetails] = useState({
name: '',
age: 0,
salary: 0,
email: ''
})
const sendData = async (event) => {
event.preventDefault()
const {name, age, salary, email} = details;
const res = await fetch("i hide the link :D",
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name, age, salary, email
})
})
navigate("/main");
}
const onSubmit = (data) => {
console.log(data)
}
return (
<div>
{show && <Confirmation show={show} setShow={setShow} />}
<div className="form-center">
<h1>Few Information</h1>
<form onSubmit={handleSubmit(sendData(), onSubmit)}>
<div className="form-controll">
<input type="text" {...register('name')} placeholder="Name"
onChange={(e) => setDetails({...details,name:e.target.value})}/>
{errors.name?.message && <p>{errors.name?.message}</p>}
<input type="number" {...register('age')} placeholder="Age"
onChange={(e) => setDetails({...details,age:e.target.value})}/>
{errors.age?.message && <p>{errors.age?.message}</p>}
<input type="number" {...register('salary')} placeholder="Salary in $"
onChange={(e) => setDetails({...details,salary:e.target.value})}/>
{errors.salary?.message && <p>{errors.salary?.message}</p>}
<input type="email" {...register('email')} placeholder="Email"
onChange={(e) => setDetails({...details,email:e.target.value})}/>
{errors.email?.message && <p>{errors.email?.message}</p>}
</div>
<div className="forgot">
Don't want to share data?<br></br>
<button onClick={() => {setShow(true)}}>Ghost mode</button>
</div>
<div className="btn">
<input type='submit' value='Go' />
</div>
</form>
</div>
</div>
)
}
handleSubmit function is a wrapper for react-hook-form to manage your data inputs, validation, errors, etc.. before calling your own sendData function.
Consider doing:
export default function LogIn() {
const sendData = async (data) => {
const {name} = data;
// your post request
}
return (
<form onSubmit={handleSubmit(sendData}> // remove the useless onSubmit
<input
type="text"
{...register('name')}
placeholder="Name"
// remove the onChange prop
/>
</form>
)
}

"Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)". How to fix Error

I'm trying to submit post form data to an my api using react and I'm passing through JSON data like so.
`
function AddSong() {
const [title, setTitle] = useState("");
const [artist, setArtist] = useState("");
const [release_date, setReleaseDate] = useState("");
const [album, setAlbum] = useState("");
const [genre, setGenre] = useState("");
let handleSubmit = async (e) => {
e.preventDefault();
try {
let res = await fetch("http://127.0.0.1:8000/api/music_library/?format=json", {
method: "POST",
body: JSON.stringify({
title: title,
artist: artist,
album: album,
release_date: release_date,
genre: genre,
}),
});
let resJson = await res.json();
if (res.status === 200) {
setTitle("");
setArtist("");
setReleaseDate("");
setAlbum("");
setGenre("");
}
} catch (err) {
console.log(err);
}
};
`
Here is my submit form.
`
return (
<div className="App">
<form onSubmit={handleSubmit}>
<input
type="text"
value={title}
placeholder="Title"
onChange={(e) => setTitle(e.target.value)}
/>
<input
type="text"
value={artist}
placeholder="Artist"
onChange={(e) => setArtist(e.target.value)}
/>
<input
type="text"
value={release_date}
placeholder="Year"
onChange={(e) => setReleaseDate(e.target.value)}
/>
<input
type="text"
value={album}
placeholder="Album"
onChange={(e) => setAlbum(e.target.value)}
/>
<input
type="text"
value={genre}
placeholder="Genre"
onChange={(e) => setGenre(e.target.value)}
/>
<button type="submit">Create</button>
</form>
</div>
);
}
export default AddSong;
`
When I click submit on the form, Chrome gives me an error saying "Failed to load resource: the server responded with a status of 415 (Unsupported Media Type)". I know it has something to do with the HandleSubmit function and the url im giving it. Im just not sure how to structure it correctly.
I tried going to the django api website and changing the get request url to JSON. I was expecting that accept the JSON data im passing through however it did not and instead gave me the same error I got when using the regular url.

Unable to retrieve API data using axios

I'm trying to build a simple login using an API but keep facing errors
import React from "react";
import { useState } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
export default function Login() {
const navigate = useNavigate();
const [formData, setFormData] = useState({
uid: "",
password: "",
blocked: 0
});
const handleSubmit = (e) => {
e.preventDefault();
console.log(formData);
const data = JSON.stringify(formData);
console.log(data);
axios
.post("https://myphysio.digitaldarwin.in/api/login/", data)
.then(function (response) {
console.log(response);
console.log("Successfully Logged in ");
navigate("/success");
})
.catch(function (error) {
console.log(error);
});
};
return (
<form onSubmit={handleSubmit}>
<h3>Login</h3>
<div className="form-group">
<label>uid Name</label>
<input
name="uid"
className="form-control"
placeholder="Enter your uid Name"
value={formData.uid}
onChange={(e) => setFormData({ ...formData, uid: e.target.value })}
/>
</div>
<div className="form-group">
<label>Password</label>
<input
type="password"
name="password"
className="form-control"
placeholder="Enter password"
value={formData.password}
onChange={(e) =>
setFormData({ ...formData, password: e.target.value })
}
/>
</div>
<button type="submit" className="btn btn-primary btn-block">
Submit
</button>
</form>
);
}
The error I keep facing is
console log of error
POST https://myphysio.digitaldarwin.in/api/login/ 500 (Internal Server Error)
Error: Network Error
at createError (createError.js:16:1)
at XMLHttpRequest.handleError (xhr.js:117:1)
POST https://myphysio.digitaldarwin.in/api/login/ net::ERR_CONTENT_LENGTH_MISMATCH 500 (Internal Server Error)
All your errors come from the backend so I suggest you to post a question in the django section (I looked at the link and I was django framework so I assume that you use django). Maybe you don't want to stringify your formData (usually it's common to send a json in a post request).

I can't find an example of how to make an HTTP POST request using useEffect hook along with axios

Lately, I've been trying to make an HTTP POST request using the useEFfect hook along with axios, but the code returns this error in the console: Error: Request failed with status code 422. The POST request is always successfully made when I make it from the form onSubmit handler. However, when I try to make it from the useEffect hook, it gives that error. Can anybody help me with what I'm doing wrong? Here's the code:
import React, { useState, useEffect } from "react";
import axios from "axios";
function RandomPost() {
const [input, setInput] = useState({
name: "",
email: "",
companyName: "",
password: "",
});
const handleChange = (event) => {
setInput({ ...input, [event.target.id]: event.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
};
useEffect(() => {
const { name, email, companyName, password } = input;
axios
.post(`https://01hire.collaq.com/user/createCompany`, input)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
}, [input]);
const { name, email, companyName, password } = input;
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Name:
<input type="text" id="name" value={name} onChange={handleChange} />
</label>
<label>
Email:
<input type="text" id="email" value={email} onChange={handleChange} />
</label>
<label>
Company Name:
<input
type="text"
id="companyName"
value={companyName}
onChange={handleChange}
/>
</label>
<label>
Password:
<input
type="password"
id="password"
value={password}
onChange={handleChange}
/>
</label>
<button type="submit">Submit</button>
</form>
</div>
);
}
export default RandomPost;

Pass multiple variable with POST method in React app

I'm trying to post multiple variables to my Postgres database using a form with React.
This is my current script:
const InputAddress = () => {
const [name, setName] = useState("");
const [problem, setProblem] = useState("");
const [date, setDate] = useState("");
const onSubmitForm = async (e) => {
e.preventDefault();
try {
const body = {
name,
problem,
date,
};
console.log(params);
const response = await fetch("http://localhost:5000/logements", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
console.log(response);
window.location = "/";
} catch (error) {
console.log(error.message);
}
};
return (
<Fragment>
<h1 className="text-center mt-5">Add your address</h1>
<form className="d-flex mt-5" onSubmit={onSubmitForm}>
<label>Name</label>
<input
type="text"
className="form-control"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<label>Comment</label>
<input
type="text"
className="form-control"
value={problem}
onChange={(e) => setProblem(e.target.value)}
/>
<label>Date</label>
<input
type="text"
className="form-control"
value={date}
onChange={(e) => setDate(e.target.value)}
/>
<button className="btn btn-success">Submit</button>
</form>
</Fragment>
);
};
My problem seems to be with the fetch method.
When I submit the form, I get this error message in the console :
bind message supplies 1 parameters, but prepared statement "" requires 3
Is there a simple fix to this problem?

Resources