I am trying to allow a user to type an ID into the form input. When they hit submit, it sends that form input value to the API url to GET the item with that ID. Currently, I see the default in the form input and can hit submit, but I can't change the value in the input. How do I allow that, so the user can modify the ID then send the request with it? Then I will handle the response with a hook
const Items: React.FC = () => {
interface Item {
id?: number;
name?: string;
}
let default = { value: "123456" };
const [item, setItem] = useState<Item>({});
const handleChange = (e: React.ChangeEvent<any>) => {
console.log(e.target.value)
};
const handleSubmit = (e: React.ChangeEvent<any>) => {
e.preventDefault();
console.log(e.target.value);
axios
.get(
`myUrl/${item:id}` <- here I want to insert the ID from the form input into the request url
)
.then((response) => setItem(response.data))
.catch((error) => console.log(error));
};
return (
<div className="toolbar-content">
<div className="row">
<form onSubmit = { handleSubmit }>
<div className="label"> MAC Address:</div>
<Input value={default.value} onChange={handleChange}/> <- here is where there should be a default value. Then if the user changes it and hits submit, send that value to the handleSubmit function
<Button className="btn" type="submit">
SUBMIT
</Button>
</form>
</div>
</div>
);
};
export default Gateways;
Thank you!
CodePudding user response:
Your handleChange function should handle this. Create a textValue state and inside the handleChange function, set the text value to the input's target value:
const Items: React.FC = () => {
interface Item {
id?: number;
name?: string;
}
let default = { value: "123456" };
const [item, setItem] = useState<Item>({});
const [textValue, setTextValue] = useState(default.value);
const handleChange = (e: React.ChangeEvent<any>) => {
setTextValue(e.target.value)
};
const handleSubmit = (e: React.ChangeEvent<any>) => {
e.preventDefault();
console.log(e.target.value);
axios
.get(
`myUrl/${item:id}` <- here I want to insert the ID from the form input into the request url
)
.then((response) => setItem(response.data))
.catch((error) => console.log(error));
};
return (
<div className="toolbar-content">
<div className="row">
<form onSubmit = { handleSubmit }>
<div className="label"> MAC Address:</div>
<Input value={textValue} onChange={handleChange}/> <- here is where there should be a default value. Then if the user changes it and hits submit, send that value to the handleSubmit function
<Button className="btn" type="submit">
SUBMIT
</Button>
</form>
</div>
</div>
);
};
export default Gateways;