Fetch in react js

Basics

  • Dont miss out the [] the second parameter
    • If you miss it , it will be infinite render
    • useEffect will call –> getLatestPosts()…it will SetPosts.. SetPosts will change posts. Because post is chaning it will call useEffect again. It renders in loop.
    • useEffect(() => {
          getLatestPosts();
        }, []);

Program

				
					import React, { useEffect, useState } from "react";
import Table from "react-bootstrap/Table";
import "bootstrap/dist/css/bootstrap.min.css";

const myBlogPostUrl = "https://clientsidecoding.com/wp-json/wp/v2/posts";

const FetchBlogPost = () => {
  const [posts, SetPosts] = useState([]);

  const getLatestPosts = async () => {
    const response = await fetch(myBlogPostUrl);
    const blogPosts = await response.json();
    SetPosts(blogPosts);
  };

  useEffect(() => {
    getLatestPosts();
  }, []);

  return (
    <>
      <div className="myClass">
        <Table style={{ width: "700px" }} striped bordered hover size="sm" variant="dark">
          <thead>
            <tr>
              <td>Post</td>
              <td>Link</td>
            </tr>
          </thead>
          {posts.map((data) => {
            return (
              <tbody>
                <tr>
                  <td>{data.slug}</td>
                  <td>
                    <a target="_blank" href={data.link}>
                      {data.link}
                    </a>
                  </td>
                </tr>
              </tbody>
            );
          })}
        </Table>
      </div>
    </>
  );
};
export default FetchBlogPost;

				
			
				
					import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import FetchBlogPost from "./FetchBlogPost";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <>
    <FetchBlogPost />
  </>
);

				
			

Leave a Comment