I'm working on building a basic form submission app using React, JS, and some basic HTML. Within the app, I'm sending the results of the form submission as a POST request to an API.
The issue I am facing is I am seeing a connection to the API (getting a 200 with each submission) but the values I am inputting to the form are appearing as undefined. I believe this is related to the use of the handleSubmit
function in my code, but I cannot figure out how to send the form data itself.
Example of my code below:
class Form extends React.Component {
constructor(props) {
super(props);
// declare input fields in state
this.state = { value: "" };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
// handle change events
handleChange = (event) => {
this.setState({
value: event.target.value,
});
};
// handle submission events
handleSubmit = (events) => {
const username = "- username -";
const password = "- password - ";
let data = `${username}:${password}`;
let encodedString = btoa(data);
let proxyLink = "- proxy URL -";
let URL = "- endpoint URL -";
let proxyURL = proxyLink + URL;
const options = {
method: "POST",
body: JSON.stringify(this.state),
headers: {
accept: "application/json",
authorization: `Basic ${encodedString}`,
},
};
fetch(proxyURL, options)
.then((response) => response.json())
.then((response) => console.log(response))
.catch((err) => console.error(err));
events.preventDefault();
};
render() {
const { values } = this.state;
return (
<form onSubmit={this.handleSubmit}>
<div>
<label>value: </label>
<input
type="text"
value={attibute_name}
onChange={this.handleChange}
name="attribute_name"
/>
</div>
</form>
);
}
}
export default Form;
I've tried changing the way I'm using handleSubmit
, even creating it as a variable and using an async function. The idea was similar to this (https://www.techomoro.com/submit-a-form-data-to-rest-api-in-a-react-app/) but it lead to worse results than what I had before.