I am creating a blog with golang gin framework rest api. When I call the block with id, my block is displayed without error on the screen, but when I call all the blogs in the data, it gives an invalid date error
main.go:
type Blog struct {
ID int `db:"id" json:"id"`
Title string `db:"title" json:"title"`
Body string `db:"body" json:"body"`
ImageURL string `db:"image" json:"image"`
Date *time.Time `db:"date" json:"date"`
}
// get blog by ID
r.GET("/blog/:id", func(c *gin.Context) {
var blog Blog
id := c.Param("id")
// get blog from database
err := db.Get(&blog, "SELECT * FROM blogs WHERE id=$1", id)
if err != nil {
if err == sql.ErrNoRows {
c.JSON(http.StatusNotFound, gin.H{"error": "blog not found"})
} else {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get blog"})
}
return
}
c.JSON(http.StatusOK, blog)
})
// get all blogs
r.GET("/blogs", func(c *gin.Context) {
var blogs []Blog
// get all blogs from database
err := db.Select(&blogs, "SELECT * FROM blogs")
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get blogs"})
return
}
c.JSON(http.StatusOK, blogs)
})
app.js:
useEffect(() => {
async function fetchData() {
try {
const response = await axios.get('http://localhost:8000/blog/1'); //this is working
setFirstPost(response.data);
} catch (error) {
setError(error.message);
}
}
fetchData();
async function fetchSecondData() {
try {
const response = await axios.get('http://localhost:8000/blogs');//not working
setSecondPost(response.data);
} catch (error) {
setError(error.message);
}
}
fetchSecondData();
}, []);
return (
<div className="blog">
<div className='blog-page'>
<h1> BLOG</h1>
</div>
{firstPost && (
<div className="blog-first">
<div className="blog-firstpage">
<img src={firstPost.image} alt={firstPost.title} />
</div>
<div className="blog-text">
<h2>{firstPost.title}</h2>
<h3>{new Date(firstPost.date).toLocaleString('en-US', { dateStyle: 'medium' })}</h3>
<p>{firstPost.body}</p>
</div>
</div>
)}
{secondPost && (
<div className="blog">
<div className="blog-secondpage">
<img src={secondPost.image} alt={secondPost.title} />
</div>
<div className="blog-text">
<h2>{secondPost.title}</h2>
<h3>{new Date(secondPost.date).toLocaleString('en-US', { dateStyle: 'medium' })}</h3>
<p>{secondPost.body}</p>
</div>
</div>
)}
{error && <p>{error}</p>}
</div>
);
}
export default Blog;