1

Blog.js

import React, { useState, useEffect } from "react"
import Axios from "axios"

const Home = () => {
  const [blog, setBlog] = useState([])
  
  useEffect(() => {
    loadBlog()
  }, [])

  const loadBlog = async () => {
    await Axios.get(`http://localhost:3001/api/blog/get`)
      .then((res) => {
        console.log(res.data.data)
        setBlog(res.data.data)
        console.log(blog)
      })
      .catch((err) => {
        console.log(err)
      })
  }

  return (
    <>
      <div className="container">
        <div className="col-lg-10">
          <h2> React CRUD Operation </h2>
        </div>
        <div className="col-lg-2">
          <button> Add Blog </button>
        </div>
        <table className="table table-striped">
          <thead>
            <tr>
              <th>ID</th>
              <th>Picture</th>
              <th>Title</th>
              <th>Short Description</th>
              <th>Author</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>{blog.id}</td>
              <td>
                <img src={"../../../public/logo512.png"} alt="not available" />
              </td>
              <td>{blog.title}</td>
              <td>{blog.short_desc}</td>
              <td>{blog.author}</td>
              <td>
                <button>Edit</button> <button>Delete</button>{" "}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </>
  )
}

export default Home

I am fetching data from API and getting data. data is coming fine but it is not going in setBlog Hook. When I console response it is fine and data is fetched successfully but problem is with it is not going in setBlog hook.I am new to react and don't know why it is not going in setBlog Hook. any help will be appreicated

5
  • is blog an object or an array of objects? Commented Aug 20, 2020 at 14:41
  • Are you basing this on the fact that console.log(blog) isn't reflecting the blog you put in via setBlog? Commented Aug 20, 2020 at 14:49
  • I tried to explain how setState works in this answer; hopefully you find it useful. You're not the only one to get confused: stackoverflow.com/a/62460109/119549 Commented Aug 20, 2020 at 14:57
  • it isarray of objects Commented Aug 20, 2020 at 17:10
  • Yes it's even not working when i want to use blog.something Commented Aug 20, 2020 at 17:20

1 Answer 1

1

This is because of the asynchronous nature of setting state. The code you have written,

.then((res) => {
        console.log(res.data.data)
        setBlog(res.data.data)
        console.log(blog)
      })

here it executes synchronously, and the actual state update happens only after this is completed. if you console log the state variable within your function body, it will be updated by next render. e.g.

const Home = () => {
  const [blog, setBlog] = useState([])
  console.log(blog)
  .
  .
  .

First time when your component loads, blog value will be set to empty array (since that is passed as argument to setState). Then your data fetch will be called and the value for blog will be set. Now the blog value will be the array that you fetched. You can use this in the rendering.

You will need to map over the items in the blog to access it. Something like the following.

.
.
.
<tbody>
  {blog.map(function (entry) {
    return (
      <tr>
        <td>{entry.id}</td>
        <td>
          <img src={"../../../public/logo512.png"} alt="not available" />
        </td>
        <td>{entry.title}</td>
        <td>{entry.short_desc}</td>
        <td>{entry.author}</td>
        <td>
          <button>Edit</button> <button>Delete</button>{" "}
        </td>
      </tr>
    );
  })}
</tbody>
.
.
.
Sign up to request clarification or add additional context in comments.

1 Comment

Then what could be the solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.