简体   繁体   中英

Fetching data from api in react

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

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. eg

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>
.
.
.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM