What are the steps to consume an API in a React app using the Fetch method

0 votes
Can i know What are the steps to consume an API in a React app using the Fetch method?
Feb 22 in Node-js by Ashutosh
• 20,870 points
43 views

1 answer to this question.

0 votes

Steps to Consume an API in a React App Using Fetch

1. Use fetch() in useEffect

import { useEffect, useState } from "react";

const API_URL = "https://jsonplaceholder.typicode.com/posts";

const FetchData = () => {

  const [data, setData] = useState([]);

  const [error, setError] = useState(null);

  useEffect(() => {

    fetch(API_URL)

      .then((response) => {

        if (!response.ok) throw new Error("Network response was not ok");

        return response.json();

      })

      .then((data) => setData(data))

      .catch((error) => setError(error.message));

  }, []);

  return (

    <div>

      {error && <p>Error: {error}</p>}

      {data.map((post) => (

        <p key={post.id}>{post.title}</p>

      ))}

    </div>

  );

};

export default FetchData;

2. Handle POST Requests

fetch(API_URL, {

  method: "POST",

  headers: { "Content-Type": "application/json" },

  body: JSON.stringify({ title: "New Post", body: "Post content" }),

})

  .then((res) => res.json())

  .then((data) => console.log(data))

  .catch((error) => console.error("Error:", error));

answered Feb 23 by Kavya

Related Questions In Node-js

0 votes
1 answer
0 votes
1 answer
0 votes
0 answers

How to handle API calls in a React app using async/await?

Can i know How to handle API ...READ MORE

1 day ago in Node-js by Ashutosh
• 20,870 points
6 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to set read concern in MongoDB?

In MongoDB, you can set read concern ...READ MORE

answered Feb 23 in Node-js by Kavya
59 views
0 votes
1 answer

What methods are available to force a component to re-render when using React hooks?

Here are the primary methods available to ...READ MORE

answered Feb 23 in Node-js by Kavya
72 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP