I am following a react tutorial and I am adding a POST request and ran into the following error:
Functions are not valid as a React child. This may happen if you return a Component instead of from render. Or maybe you meant to call this function rather than return it.
Before this I was looking at submit events, and everything was fine. The website still runs but I’m getting a fetch aborted
message when I inspect my console.
I know They are a lot of similar errors on Stack overflow already and have reviewed several. I’ve seen a lot of problems and solutions, understood some. But none of them fit what I’m trying to do. Note: I’m a complete beginner in react this is my first web-application. The error only popped up after adding my POST request .
Create.js
import { useState } from "react";
const Create = () => {
const [title, setTitle] = useState('');
const [body, setBody] = useState('');
const [author, setAuthor] = useState('mario');
const [isLoading, setIsLoading] = useState(false);
//Submit events
const handleSubmit = (e) => {
e.preventDefault();
const blog = { title, body, author };
setIsLoading(true);
//POST request
fetch("http://localhost:8000/blogs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(blog),
}).then(() => {
console.log("new blog added");
setIsLoading(false);
});
}
return (
<div className="create">
<h2>Add a new blog</h2>
//Input form
<form onSubmit={ handleSubmit } >
<label>Blog title</label>
<input
type="text"
required
value={ title }
onChange={(e) => setTitle(e.target.value)}
/>
<label>Blog body</label>
<textarea
required
value={ body }
onChange={(e) => setBody(e.target.value)}
></textarea>
<label>Blog author</label>
<select>
//Blog author
value={ author}
onChange={(e) => setAuthor(e.target.value)}
<option value="mario">Mario</option>
<option value="yoshi">Yoshi</option>
</select>
</form>
//Button
{ !isLoading && <button>Add blog</button> }
{ isLoading && <button disabled>Adding blog...</button> }
<p>{ title }</p>
<p>{ body }</p>
<p>{ author }</p>
</div>
);
}
export default Create;