How to add fetch in the above code I was trying to call a rest API using fetch in setEffect but I am getting the error.
Goal: to call the rest API when I submit the form. Till now I was able to generate URL dynamically from form and was unable to connect to fetch and call the rest API.
const { useState } = React;
function Example() {
const [ form, setForm ] = useState({});
function handleSubmit() {
const uri = `http://example.com/?${form.one}&${form.two}`;
console.log(`Current state: ${JSON.stringify(form)}`);
console.log(`Fetch URI: ${uri}`);
// fetch(uri)... etc
}
function handleChange(e) {
const { nodeName, name, value } = e.target;
if (nodeName === 'INPUT') {
setForm({ ...form, [name]: value });
}
}
return (
<form onChange={handleChange}>
<fieldset>
<legend>Input one</legend>
<input name="one" value={form.one} />
</fieldset>
<fieldset>
<legend>Input two</legend>
<input name="two" value={form.two} />
</fieldset>
<button type="button" onClick={handleSubmit}>Submit</button>
</form>
);
};
ReactDOM.render(
<Example />,
document.getElementById('react')
);
To start, onChange should be on the input elements, not the form. you should make the button type="submit". you should add onSubmit={handleSubmit} on the form. inside handleSubmit you should add the event and prevent the default behavior handleSubmit(e) { e.preventDefault(); ... }.
then you can call your fetch api in handleSubmit.
const { useState } = React;
function Example() {
const [ form, setForm ] = useState({one:'',two:''});
function handleSubmit(e) {
e.preventDefault();
const uri = `http://example.com/?${form.one}&${form.two}`;
fetch(uri, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.)
body: JSON.stringify(form),
}).then(r=>{
console.log(r)
})
// console.log(`Current state: ${JSON.stringify(form)}`);
// console.log(`Fetch URI: ${uri}`);
// fetch(uri)... etc
}
function handleChange(e) {
const { nodeName, name, value } = e.target;
if (nodeName === 'INPUT') {
setForm({ ...form, [name]: value });
}
}
return (
<div >
<form onChange={handleSubmit}>
<fieldset>
<legend>Input one</legend>
<input name="one" value={form.one} onChange={handleChange}/>
</fieldset>
<fieldset>
<legend>Input two</legend>
<input name="two" value={form.two} onChange={handleChange}/>
</fieldset>
<button type="button" onClick={handleSubmit}>Submit</button>
</form>
</div>
);
};
ReactDOM.render(
<Example />,
document.getElementById('react')
);
that works for me very well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.