I'm trying to send some user input values into my SQL Server table. The question is when I tried the hardcoded values it works a charm and send the data to the table. But when I'm storing and getting user inputs via useState
hook it does not work.
When I mean it does not work:
- No errors get thrown
- I see
response.data
as an empty string. Ex:data: ''
Now following is my Test.js
:
import React, { useState } from 'react'
import axios from 'axios';
const Test = () => {
const [machine, setMachine] = useState('');
const [empID, setEmpID] = useState(0);
const handleMachine = event => {
setMachine({machine : event.target.value});
console.log(setMachine);
}
const handleEmp = event => {
setEmpID({emp_no : event.target.value});
console.log(setEmpID);
}
const handleSubmit = event => {
event.preventDefault();
console.log(machine, empID);
axios.post('http://localhost:8090/api/ctms/employees/loggedin',{
machine: machine, //this is the first user input but if I hard-code it Ex:'MAC1' it works
emp_no: empID, //Again same for the second user input, only hard-code works
date_on: '07/11/2022'
})
.then(function (response) {
console.log(response);
console.log(response.data);
})
.catch(function (error) {
console.log(error);
console.log(error.data);
});
}
return (
<div>
<form onSubmit={handleSubmit}>
<label>
Machine:
<input type="text" name="machine" onChange={handleMachine} />
</label>
<label>
EMP ID:
<input type="text" name="emp_no" onChange={handleEmp} />
</label>
<button type="submit">Add</button>
</form>
</div>
)
}
export default Test;
SQL Server table which data goes into. Here all the rows were input as hard-coded values.
Finally following is the React console output after submitting the form.
CodePudding user response:
You're not setting the state variables to a primitive string value but an object, and it's clear {machine : 'string'}
is not equal to 'string'
. Just change setMachine({machine : event.target.value})
to setMachine(event.target.value)
; same goes for empID
.